├── .gitignore ├── src ├── main │ └── java │ │ └── pro │ │ └── edgematrix │ │ ├── protocol │ │ ├── methods │ │ │ └── response │ │ │ │ ├── EdgeSendRtcMsg.java │ │ │ │ ├── EdgeSendTelegram.java │ │ │ │ └── EdgeCallResult.java │ │ └── core │ │ │ └── JsonRpc2_0Web3j.java │ │ ├── common │ │ ├── ChainId.java │ │ └── PrecompileAddress.java │ │ ├── crypto │ │ ├── type │ │ │ ├── IRtcMsg.java │ │ │ ├── ITelegram.java │ │ │ ├── RtcMsgType.java │ │ │ ├── RtcMsg.java │ │ │ └── Telegram.java │ │ ├── RawRtcMsg.java │ │ ├── RtcMsgEncoder.java │ │ ├── RawTelegram.java │ │ ├── TelegramEncoder.java │ │ └── Sign.java │ │ ├── RtcMsg.java │ │ ├── EdgeWeb3j.java │ │ └── EdgeService.java └── test │ └── java │ └── pro │ └── edgematrix │ └── crypto │ ├── SampleKeys.java │ ├── RtcMsgEncoderTest.java │ ├── TelegramEncoderTest.java │ └── EdgeServiceTest.java ├── pom.xml ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | /.idea/ 2 | -------------------------------------------------------------------------------- /src/main/java/pro/edgematrix/protocol/methods/response/EdgeSendRtcMsg.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Web3 Labs Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 5 | * the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on 10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the 11 | * specific language governing permissions and limitations under the License. 12 | */ 13 | package pro.edgematrix.protocol.methods.response; 14 | 15 | import org.web3j.protocol.core.Response; 16 | 17 | /** edge_sendRawMsg */ 18 | public class EdgeSendRtcMsg extends Response { 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/pro/edgematrix/protocol/methods/response/EdgeSendTelegram.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Web3 Labs Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 5 | * the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on 10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the 11 | * specific language governing permissions and limitations under the License. 12 | */ 13 | package pro.edgematrix.protocol.methods.response; 14 | 15 | import org.web3j.protocol.core.Response; 16 | 17 | /** edge_sendRawTelegram. */ 18 | public class EdgeSendTelegram extends Response { 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/pro/edgematrix/common/ChainId.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 edgematrix Labs Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 5 | * the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on 10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the 11 | * specific language governing permissions and limitations under the License. 12 | */ 13 | package pro.edgematrix.common; 14 | 15 | public enum ChainId { 16 | MAIN_NET(1), 17 | TEST_NET(2); 18 | 19 | private int id; 20 | 21 | ChainId(int id) { 22 | this.id = id; 23 | } 24 | 25 | public int getId() { 26 | return id; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/pro/edgematrix/common/PrecompileAddress.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 edgematrix Labs Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 5 | * the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on 10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the 11 | * specific language governing permissions and limitations under the License. 12 | */ 13 | package pro.edgematrix.common; 14 | 15 | public enum PrecompileAddress { 16 | EDGE_RTC_SUBJECT("0x0000000000000000000000000000000000003101"), 17 | EDGE_CALL("0x0000000000000000000000000000000000003001"); 18 | 19 | private String address; 20 | 21 | PrecompileAddress(String addr) { 22 | this.address = addr; 23 | } 24 | 25 | public String getAddress() { 26 | return address; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/pro/edgematrix/crypto/type/IRtcMsg.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 edgematrix Labs Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 5 | * the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on 10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the 11 | * specific language governing permissions and limitations under the License. 12 | */ 13 | package pro.edgematrix.crypto.type; 14 | 15 | import org.web3j.rlp.RlpType; 16 | import pro.edgematrix.crypto.Sign; 17 | 18 | import java.util.List; 19 | 20 | public interface IRtcMsg { 21 | 22 | List asRlpValues(Sign.SignatureData signatureData); 23 | 24 | String getSubject(); 25 | 26 | String getApplication(); 27 | 28 | String getContent(); 29 | 30 | String getTo(); 31 | 32 | RtcMsgType getType(); 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/pro/edgematrix/crypto/type/ITelegram.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Web3 Labs Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 5 | * the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on 10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the 11 | * specific language governing permissions and limitations under the License. 12 | */ 13 | package pro.edgematrix.crypto.type; 14 | 15 | import org.web3j.crypto.Sign; 16 | import org.web3j.crypto.transaction.type.TransactionType; 17 | import org.web3j.rlp.RlpType; 18 | 19 | import java.math.BigInteger; 20 | import java.util.List; 21 | 22 | public interface ITelegram { 23 | 24 | List asRlpValues(Sign.SignatureData signatureData); 25 | 26 | BigInteger getNonce(); 27 | 28 | BigInteger getGasPrice(); 29 | 30 | BigInteger getGasLimit(); 31 | 32 | String getTo(); 33 | 34 | BigInteger getValue(); 35 | 36 | String getData(); 37 | 38 | TransactionType getType(); 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/pro/edgematrix/protocol/methods/response/EdgeCallResult.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Web3 Labs Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 5 | * the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on 10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the 11 | * specific language governing permissions and limitations under the License. 12 | */ 13 | package pro.edgematrix.protocol.methods.response; 14 | 15 | /** EdgeCallResponse. */ 16 | public class EdgeCallResult { 17 | private String telegram_hash; 18 | private String response; 19 | 20 | public String getTelegram_hash() { 21 | return telegram_hash; 22 | } 23 | 24 | public void setTelegram_hash(String telegram_hash) { 25 | this.telegram_hash = telegram_hash; 26 | } 27 | 28 | public String getResponse() { 29 | return response; 30 | } 31 | 32 | public void setResponse(String response) { 33 | this.response = response; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | pro.edge-matrix 8 | edge-matrix-sdk-java 9 | 1.1-SNAPSHOT 10 | 11 | 12 | UTF-8 13 | UTF-8 14 | 8 15 | 8 16 | true 17 | 18 | 19 | 20 | 21 | org.junit.jupiter 22 | junit-jupiter 23 | 5.5.2 24 | test 25 | 26 | 27 | org.web3j 28 | core 29 | 4.9.7 30 | 31 | 32 | -------------------------------------------------------------------------------- /src/main/java/pro/edgematrix/crypto/type/RtcMsgType.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 edgematrix Labs Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 5 | * the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on 10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the 11 | * specific language governing permissions and limitations under the License. 12 | */ 13 | package pro.edgematrix.crypto.type; 14 | 15 | 16 | public enum RtcMsgType { 17 | SubjectMsg(((byte) 0x0)), 18 | StateMsg(((byte) 0x01)), 19 | SubscribeMsg(((byte) 0x02)); 20 | 21 | Byte type; 22 | 23 | RtcMsgType(final Byte type) { 24 | this.type = type; 25 | } 26 | 27 | public Byte getRlpType() { 28 | return type; 29 | } 30 | 31 | public boolean isSubject() { 32 | return this.equals(RtcMsgType.SubjectMsg); 33 | } 34 | 35 | public boolean isState() { 36 | return this.equals(RtcMsgType.StateMsg); 37 | } 38 | 39 | public boolean isSubscribe() { 40 | return this.equals(RtcMsgType.SubscribeMsg); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/test/java/pro/edgematrix/crypto/SampleKeys.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 edgematrix Labs Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 5 | * the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on 10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the 11 | * specific language governing permissions and limitations under the License. 12 | */ 13 | package pro.edgematrix.crypto; 14 | 15 | import org.web3j.crypto.Credentials; 16 | import org.web3j.crypto.ECKeyPair; 17 | import org.web3j.utils.Numeric; 18 | 19 | import java.math.BigInteger; 20 | 21 | /** 22 | * Keys generated for unit testing purposes. 23 | */ 24 | public class SampleKeys { 25 | 26 | public static final String PRIVATE_KEY_STRING = 27 | "03b7dfc824b0cbcfe789ec0ce4571f3460befd0490e3d0d2aad8e3c07dbcce14"; 28 | public static final String ADDRESS = "0x0aF137aa3EcC7d10d926013ee34049AfA77382e6"; 29 | public static final String ADDRESS_NO_PREFIX = Numeric.cleanHexPrefix(ADDRESS); 30 | 31 | 32 | static final BigInteger PRIVATE_KEY = Numeric.toBigInt(PRIVATE_KEY_STRING); 33 | 34 | static final ECKeyPair KEY_PAIR = ECKeyPair.create(PRIVATE_KEY); 35 | 36 | public static final Credentials CREDENTIALS = Credentials.create(KEY_PAIR); 37 | 38 | private SampleKeys() { 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/pro/edgematrix/RtcMsg.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 edgematrix Labs Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 5 | * the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on 10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the 11 | * specific language governing permissions and limitations under the License. 12 | */ 13 | package pro.edgematrix; 14 | 15 | /** 16 | * rtc message 17 | */ 18 | public class RtcMsg { 19 | 20 | // RTC channel hash. 21 | private String subject; 22 | 23 | // application name the rtc channel belongs to 24 | private String application; 25 | 26 | // rtc text content. 27 | private String content; 28 | 29 | // address of rtc message to. 30 | // 0x0 is broadcast address 31 | private String to; 32 | 33 | public static RtcMsg createRtcMsg( 34 | String subject, String application, String content, String to) { 35 | RtcMsg rtcMsg = new RtcMsg(); 36 | rtcMsg.application = application; 37 | rtcMsg.subject = subject; 38 | rtcMsg.to = to; 39 | rtcMsg.content = content; 40 | return rtcMsg; 41 | } 42 | 43 | public String getSubject() { 44 | return subject; 45 | } 46 | 47 | public void setSubject(String subject) { 48 | this.subject = subject; 49 | } 50 | 51 | public String getApplication() { 52 | return application; 53 | } 54 | 55 | public void setApplication(String application) { 56 | this.application = application; 57 | } 58 | 59 | public String getContent() { 60 | return content; 61 | } 62 | 63 | public void setContent(String content) { 64 | this.content = content; 65 | } 66 | 67 | public String getTo() { 68 | return to; 69 | } 70 | 71 | public void setTo(String to) { 72 | this.to = to; 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/pro/edgematrix/EdgeWeb3j.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 edgematrix Labs Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 5 | * the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on 10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the 11 | * specific language governing permissions and limitations under the License. 12 | */ 13 | package pro.edgematrix; 14 | 15 | import org.web3j.protocol.Web3jService; 16 | import org.web3j.protocol.core.Batcher; 17 | import org.web3j.protocol.core.DefaultBlockParameter; 18 | import org.web3j.protocol.core.Ethereum; 19 | import org.web3j.protocol.core.Request; 20 | import org.web3j.protocol.core.methods.response.EthGetTransactionCount; 21 | import org.web3j.protocol.core.methods.response.EthGetTransactionReceipt; 22 | import org.web3j.protocol.rx.Web3jRx; 23 | import pro.edgematrix.protocol.core.JsonRpc2_0Web3j; 24 | import pro.edgematrix.protocol.methods.response.EdgeSendRtcMsg; 25 | import pro.edgematrix.protocol.methods.response.EdgeSendTelegram; 26 | 27 | /** 28 | * egde-matrix JSON-RPC Request object building factory. 29 | */ 30 | public interface EdgeWeb3j extends Ethereum, Web3jRx, Batcher { 31 | 32 | Request edgeGetTelegramReceipt(String telegramHash); 33 | 34 | Request edgeGetTelegramCount( 35 | String address, DefaultBlockParameter defaultBlockParameter); 36 | 37 | Request edgeSendRawTelegram(String var1); 38 | 39 | Request edgeSendRawMsg(String var1); 40 | 41 | /** 42 | * Construct a new EdgeWeb3j instance. 43 | * 44 | * @param web3jService web3j service instance - i.e. HTTP or IPC 45 | * @return new EdgeWeb3j instance 46 | */ 47 | static EdgeWeb3j build(Web3jService web3jService) { 48 | return new JsonRpc2_0Web3j(web3jService); 49 | } 50 | 51 | /** 52 | * Shutdowns a EdgeWeb3j instance and closes opened resources. 53 | */ 54 | void shutdown(); 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/pro/edgematrix/crypto/RawRtcMsg.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 edgematrix Labs Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 5 | * the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on 10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the 11 | * specific language governing permissions and limitations under the License. 12 | */ 13 | package pro.edgematrix.crypto; 14 | 15 | import org.web3j.rlp.RlpType; 16 | import pro.edgematrix.crypto.type.IRtcMsg; 17 | import pro.edgematrix.crypto.type.RtcMsg; 18 | import pro.edgematrix.crypto.type.RtcMsgType; 19 | 20 | import java.util.List; 21 | 22 | /** 23 | * RawRtcMsg class used for signing RawRtcMsg locally.
24 | * For the specification, refer to yellow 25 | * paper. 26 | */ 27 | public class RawRtcMsg { 28 | 29 | private final IRtcMsg transaction; 30 | 31 | protected RawRtcMsg(final IRtcMsg transaction) { 32 | this.transaction = transaction; 33 | } 34 | 35 | 36 | public static RawRtcMsg createRtcMsg( 37 | String subject, String application, String content, String to) { 38 | return new RawRtcMsg( 39 | RtcMsg.createContractTransaction( 40 | subject, application, content, to)); 41 | } 42 | 43 | public List asRlpValues(Sign.SignatureData signatureData) { 44 | return transaction.asRlpValues(signatureData); 45 | } 46 | 47 | public String getSubject() { 48 | return transaction.getSubject(); 49 | } 50 | 51 | public String getApplication() { 52 | return transaction.getApplication(); 53 | } 54 | 55 | public String getContent() { 56 | return transaction.getContent(); 57 | } 58 | 59 | public String getTo() { 60 | return transaction.getTo(); 61 | } 62 | 63 | public RtcMsgType getType() { 64 | return transaction.getType(); 65 | } 66 | 67 | public IRtcMsg getTransaction() { 68 | return transaction; 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/test/java/pro/edgematrix/crypto/RtcMsgEncoderTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 edgematrix Labs Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 5 | * the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on 10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the 11 | * specific language governing permissions and limitations under the License. 12 | */ 13 | package pro.edgematrix.crypto; 14 | 15 | import org.junit.jupiter.api.Test; 16 | import org.web3j.abi.datatypes.Address; 17 | import org.web3j.utils.Numeric; 18 | import pro.edgematrix.common.ChainId; 19 | 20 | import static org.junit.jupiter.api.Assertions.assertEquals; 21 | 22 | public class RtcMsgEncoderTest { 23 | 24 | // Example from https://eips.ethereum.org/EIPS/eip-155 25 | private final String SIGN_RESULT_EXAMPLE = 26 | "0xf8acb84230783865656233333832333961646132326438316666623761646339393566653331613464316463326437303162633861353866666665356235336531343238316589656467655f636861748568656c6c6f94000000000000000000000000000000000000000028a0c2ef640e01996a92a323233b847348b8ab3107673e4ad120c6561a24a24e1267a060e348a187ed7bd7668783ebe1e87db36d59ea72cda99560dc78c048668b42d2"; 27 | 28 | @Test 29 | public void testSignMessageAfterEip155() { 30 | byte[] signedMessage = 31 | RtcMsgEncoder.signMessage( 32 | createRtcMsg(), 33 | ChainId.TEST_NET.getId(), 34 | SampleKeys.CREDENTIALS); 35 | 36 | String hexMessage = Numeric.toHexString(signedMessage); 37 | System.out.println("Actual : " + hexMessage); 38 | System.out.println("Expected: " + SIGN_RESULT_EXAMPLE); 39 | assertEquals(SIGN_RESULT_EXAMPLE, hexMessage); 40 | } 41 | 42 | private static RawRtcMsg createRtcMsg() { 43 | return RawRtcMsg.createRtcMsg( 44 | "0x8eeb338239ada22d81ffb7adc995fe31a4d1dc2d701bc8a58fffe5b53e14281e", 45 | "edge_chat", 46 | "hello", 47 | new Address("0x0").toString()); 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/pro/edgematrix/crypto/type/RtcMsg.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 edgematrix Labs Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 5 | * the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on 10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the 11 | * specific language governing permissions and limitations under the License. 12 | */ 13 | package pro.edgematrix.crypto.type; 14 | 15 | import org.web3j.rlp.RlpString; 16 | import org.web3j.rlp.RlpType; 17 | import org.web3j.utils.Bytes; 18 | import org.web3j.utils.Numeric; 19 | import pro.edgematrix.crypto.Sign; 20 | 21 | import java.util.ArrayList; 22 | import java.util.List; 23 | 24 | /** 25 | * RtcMsg class used for signing RtcMsg locally.
26 | * For the specification, refer to yellow 27 | * paper. 28 | */ 29 | public class RtcMsg implements IRtcMsg { 30 | 31 | private RtcMsgType type; 32 | 33 | String subject; 34 | String application; 35 | String content; 36 | String to; 37 | 38 | public RtcMsg(String subject, String application, String content, String to) { 39 | this.subject = subject; 40 | this.application = application; 41 | this.content = content; 42 | this.to = to; 43 | this.type = RtcMsgType.SubscribeMsg; 44 | } 45 | 46 | @Override 47 | public List asRlpValues(Sign.SignatureData signatureData) { 48 | List result = new ArrayList<>(); 49 | 50 | result.add(RlpString.create(getSubject())); 51 | 52 | result.add(RlpString.create(getApplication())); 53 | result.add(RlpString.create(getContent())); 54 | 55 | // an empty to address should not be encoded as a numeric 0 value 56 | String to = getTo(); 57 | if (to != null && to.length() > 0) { 58 | // addresses that start with zeros should be encoded with the zeros included, not 59 | // as numeric values 60 | result.add(RlpString.create(Numeric.hexStringToByteArray(to))); 61 | } else { 62 | result.add(RlpString.create("")); 63 | } 64 | 65 | if (signatureData != null) { 66 | result.add(RlpString.create(Bytes.trimLeadingZeroes(signatureData.getV()))); 67 | result.add(RlpString.create(Bytes.trimLeadingZeroes(signatureData.getR()))); 68 | result.add(RlpString.create(Bytes.trimLeadingZeroes(signatureData.getS()))); 69 | } 70 | 71 | return result; 72 | } 73 | 74 | public static RtcMsg createContractTransaction( 75 | String subject, String application, String content, String to) { 76 | 77 | return new RtcMsg(subject, application, content, to); 78 | } 79 | 80 | @Override 81 | public RtcMsgType getType() { 82 | return type; 83 | } 84 | 85 | public String getSubject() { 86 | return subject; 87 | } 88 | 89 | public String getApplication() { 90 | return application; 91 | } 92 | 93 | public String getContent() { 94 | return content; 95 | } 96 | 97 | @Override 98 | public String getTo() { 99 | return to; 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/main/java/pro/edgematrix/crypto/RtcMsgEncoder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 edgematrix Labs Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 5 | * the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on 10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the 11 | * specific language governing permissions and limitations under the License. 12 | */ 13 | package pro.edgematrix.crypto; 14 | 15 | import org.web3j.crypto.Credentials; 16 | import org.web3j.rlp.RlpEncoder; 17 | import org.web3j.rlp.RlpList; 18 | import org.web3j.rlp.RlpType; 19 | import org.web3j.utils.Numeric; 20 | 21 | import java.math.BigInteger; 22 | import java.nio.ByteBuffer; 23 | import java.util.List; 24 | 25 | import static org.web3j.crypto.Sign.CHAIN_ID_INC; 26 | import static org.web3j.crypto.Sign.LOWER_REAL_V; 27 | 28 | /** 29 | * Create RLP encoded transaction, implementation yellow 30 | * paper. 31 | */ 32 | public class RtcMsgEncoder { 33 | 34 | /** 35 | * Use for RtcMsg 36 | * 37 | * @return signature 38 | */ 39 | public static byte[] signMessage( 40 | RawRtcMsg rawTransaction, long chainId, Credentials credentials) { 41 | 42 | byte[] encodedTransaction = encode(rawTransaction, chainId); 43 | Sign.SignatureData signatureData = 44 | Sign.signMessage(encodedTransaction, credentials.getEcKeyPair()); 45 | 46 | Sign.SignatureData eip155SignatureData = createEip155SignatureData(signatureData, chainId); 47 | return encode(rawTransaction, eip155SignatureData); 48 | } 49 | 50 | public static Sign.SignatureData createEip155SignatureData( 51 | Sign.SignatureData signatureData, long chainId) { 52 | BigInteger v = Numeric.toBigInt(signatureData.getV()); 53 | v = v.subtract(BigInteger.valueOf(LOWER_REAL_V)); 54 | v = v.add(BigInteger.valueOf(chainId).multiply(BigInteger.valueOf(2))); 55 | v = v.add(BigInteger.valueOf(CHAIN_ID_INC)); 56 | 57 | return new Sign.SignatureData(v.toByteArray(), signatureData.getR(), signatureData.getS()); 58 | } 59 | 60 | public static byte[] encode(RawRtcMsg rawTransaction) { 61 | return encode(rawTransaction, null); 62 | } 63 | 64 | /** 65 | * Encode RtcMsg with chainId together 66 | * 67 | * @return encoded bytes 68 | */ 69 | public static byte[] encode(RawRtcMsg rawTransaction, long chainId) { 70 | Sign.SignatureData signatureData = 71 | new Sign.SignatureData(longToBytes(chainId), new byte[]{}, new byte[]{}); 72 | return encode(rawTransaction, signatureData); 73 | } 74 | 75 | public static byte[] encode(RawRtcMsg rawTransaction, Sign.SignatureData signatureData) { 76 | List values = asRlpValues(rawTransaction, signatureData); 77 | RlpList rlpList = new RlpList(values); 78 | byte[] encoded = RlpEncoder.encode(rlpList); 79 | 80 | return encoded; 81 | } 82 | 83 | private static byte[] longToBytes(long x) { 84 | ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES); 85 | buffer.putLong(x); 86 | return buffer.array(); 87 | } 88 | 89 | public static List asRlpValues( 90 | RawRtcMsg rawTransaction, Sign.SignatureData signatureData) { 91 | return rawTransaction.getTransaction().asRlpValues(signatureData); 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/main/java/pro/edgematrix/crypto/RawTelegram.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 edgematrix Labs Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 5 | * the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on 10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the 11 | * specific language governing permissions and limitations under the License. 12 | */ 13 | package pro.edgematrix.crypto; 14 | 15 | import org.web3j.crypto.transaction.type.ITransaction; 16 | import org.web3j.crypto.transaction.type.LegacyTransaction; 17 | import org.web3j.crypto.transaction.type.TransactionType; 18 | import org.web3j.utils.Numeric; 19 | 20 | import java.math.BigInteger; 21 | import java.nio.charset.StandardCharsets; 22 | 23 | /** 24 | * Transaction class used for signing transactions locally.
25 | * For the specification, refer to p4 of the yellow 26 | * paper. 27 | */ 28 | public class RawTelegram { 29 | 30 | private final ITransaction transaction; 31 | 32 | protected RawTelegram(final ITransaction transaction) { 33 | this.transaction = transaction; 34 | } 35 | 36 | protected RawTelegram( 37 | BigInteger nonce, 38 | BigInteger gasPrice, 39 | BigInteger gasLimit, 40 | String to, 41 | BigInteger value, 42 | String data) { 43 | this(new LegacyTransaction(nonce, gasPrice, gasLimit, to, value, Numeric.toHexString(data.getBytes(StandardCharsets.UTF_8)))); 44 | } 45 | 46 | public static RawTelegram createContractTransaction( 47 | BigInteger nonce, 48 | BigInteger gasPrice, 49 | BigInteger gasLimit, 50 | BigInteger value, 51 | String init) { 52 | return new RawTelegram( 53 | LegacyTransaction.createContractTransaction( 54 | nonce, gasPrice, gasLimit, value, init)); 55 | } 56 | 57 | public static RawTelegram createEtherTransaction( 58 | BigInteger nonce, 59 | BigInteger gasPrice, 60 | BigInteger gasLimit, 61 | String to, 62 | BigInteger value) { 63 | 64 | return new RawTelegram( 65 | LegacyTransaction.createEtherTransaction(nonce, gasPrice, gasLimit, to, value)); 66 | } 67 | 68 | public static RawTelegram createTransaction( 69 | BigInteger nonce, 70 | BigInteger gasPrice, 71 | BigInteger gasLimit, 72 | String to, 73 | BigInteger value, 74 | String data) { 75 | 76 | return new RawTelegram( 77 | LegacyTransaction.createTransaction(nonce, gasPrice, gasLimit, to, value, Numeric.toHexString(data.getBytes(StandardCharsets.UTF_8)))); 78 | } 79 | 80 | 81 | public BigInteger getNonce() { 82 | return transaction.getNonce(); 83 | } 84 | 85 | public BigInteger getGasPrice() { 86 | return transaction.getGasPrice(); 87 | } 88 | 89 | public BigInteger getGasLimit() { 90 | return transaction.getGasLimit(); 91 | } 92 | 93 | public String getTo() { 94 | return transaction.getTo(); 95 | } 96 | 97 | public BigInteger getValue() { 98 | return transaction.getValue(); 99 | } 100 | 101 | public String getData() { 102 | return transaction.getData(); 103 | } 104 | 105 | public TransactionType getType() { 106 | return transaction.getType(); 107 | } 108 | 109 | public ITransaction getTransaction() { 110 | return transaction; 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /src/main/java/pro/edgematrix/crypto/TelegramEncoder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 edgematrix Labs Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 5 | * the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on 10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the 11 | * specific language governing permissions and limitations under the License. 12 | */ 13 | package pro.edgematrix.crypto; 14 | 15 | import org.web3j.crypto.Credentials; 16 | import org.web3j.crypto.Sign; 17 | import org.web3j.crypto.exception.CryptoWeb3jException; 18 | import org.web3j.rlp.RlpEncoder; 19 | import org.web3j.rlp.RlpList; 20 | import org.web3j.rlp.RlpType; 21 | import org.web3j.utils.Numeric; 22 | 23 | import java.math.BigInteger; 24 | import java.nio.ByteBuffer; 25 | import java.util.List; 26 | 27 | import static org.web3j.crypto.Sign.CHAIN_ID_INC; 28 | import static org.web3j.crypto.Sign.LOWER_REAL_V; 29 | 30 | /** 31 | * Create RLP encoded transaction, implementation as per p4 of the yellow paper. 33 | */ 34 | public class TelegramEncoder { 35 | 36 | /** 37 | * Use for new transactions Eip1559 (this txs has a new field chainId) or an old one before 38 | * Eip155 39 | * 40 | * @return signature 41 | */ 42 | public static byte[] signMessage(RawTelegram rawTransaction, Credentials credentials) { 43 | byte[] encodedTransaction = encode(rawTransaction); 44 | org.web3j.crypto.Sign.SignatureData signatureData = 45 | org.web3j.crypto.Sign.signMessage(encodedTransaction, credentials.getEcKeyPair()); 46 | 47 | return encode(rawTransaction, signatureData); 48 | } 49 | 50 | /** 51 | * Use for legacy txs (after Eip155 before Eip1559) 52 | * 53 | * @return signature 54 | */ 55 | public static byte[] signMessage( 56 | RawTelegram rawTransaction, long chainId, Credentials credentials) { 57 | 58 | // Eip1559: Tx has ChainId inside 59 | if (rawTransaction.getType().isEip1559()) { 60 | return signMessage(rawTransaction, credentials); 61 | } 62 | 63 | byte[] encodedTransaction = encode(rawTransaction, chainId); 64 | org.web3j.crypto.Sign.SignatureData signatureData = 65 | org.web3j.crypto.Sign.signMessage(encodedTransaction, credentials.getEcKeyPair()); 66 | 67 | org.web3j.crypto.Sign.SignatureData eip155SignatureData = createEip155SignatureData(signatureData, chainId); 68 | return encode(rawTransaction, eip155SignatureData); 69 | } 70 | 71 | 72 | public static org.web3j.crypto.Sign.SignatureData createEip155SignatureData( 73 | org.web3j.crypto.Sign.SignatureData signatureData, long chainId) { 74 | BigInteger v = Numeric.toBigInt(signatureData.getV()); 75 | v = v.subtract(BigInteger.valueOf(LOWER_REAL_V)); 76 | v = v.add(BigInteger.valueOf(chainId).multiply(BigInteger.valueOf(2))); 77 | v = v.add(BigInteger.valueOf(CHAIN_ID_INC)); 78 | 79 | return new org.web3j.crypto.Sign.SignatureData(v.toByteArray(), signatureData.getR(), signatureData.getS()); 80 | } 81 | 82 | 83 | public static byte[] encode(RawTelegram rawTransaction) { 84 | return encode(rawTransaction, null); 85 | } 86 | 87 | /** 88 | * Encode transaction with chainId together, it make sense only for Legacy transactions 89 | * 90 | * @return encoded bytes 91 | */ 92 | public static byte[] encode(RawTelegram rawTransaction, long chainId) { 93 | if (!rawTransaction.getType().isLegacy()) { 94 | throw new CryptoWeb3jException("Incorrect transaction type. Tx type should be Legacy."); 95 | } 96 | 97 | org.web3j.crypto.Sign.SignatureData signatureData = 98 | new org.web3j.crypto.Sign.SignatureData(longToBytes(chainId), new byte[]{}, new byte[]{}); 99 | return encode(rawTransaction, signatureData); 100 | } 101 | 102 | public static byte[] encode(RawTelegram rawTransaction, org.web3j.crypto.Sign.SignatureData signatureData) { 103 | List values = asRlpValues(rawTransaction, signatureData); 104 | RlpList rlpList = new RlpList(values); 105 | byte[] encoded = RlpEncoder.encode(rlpList); 106 | 107 | if (rawTransaction.getType().isEip1559() || rawTransaction.getType().isEip2930()) { 108 | return ByteBuffer.allocate(encoded.length + 1) 109 | .put(rawTransaction.getType().getRlpType()) 110 | .put(encoded) 111 | .array(); 112 | } 113 | return encoded; 114 | } 115 | 116 | private static byte[] longToBytes(long x) { 117 | ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES); 118 | buffer.putLong(x); 119 | return buffer.array(); 120 | } 121 | 122 | public static List asRlpValues( 123 | RawTelegram rawTransaction, Sign.SignatureData signatureData) { 124 | return rawTransaction.getTransaction().asRlpValues(signatureData); 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | EMC Java SDK 2 | ================================== 3 | 4 | 5 | emc_java_sdk is a lightweight Java library for integrating with clients (nodes) on the edge-matrix network: 6 | 7 | This allows you to work with the [EdgeMatrix](https://www.edgematrix.pro/) 8 | Decentralized Computing Network, without the additional overhead of having to write your own integration code for the 9 | platform. 10 | 11 | 12 | QuickStart 13 | --------- 14 | The simplest way to start your journey with emc_java_sdk is to create a project. 15 | 16 | #### Please head to the [EdgeMatrix](https://www.edgematrix.pro/) for further instructions on using emc Java SDK. 17 | 18 | Maven 19 | ----- 20 | 21 | 22 | #### Depoly jar to your local maven repository 23 | 24 | $ mvn install:install-file -Dfile=/local/path/edge-matrix-sdk-java-1.1-SNAPSHOT.jar -DgroupId=pro.edge-matrix 25 | -DartifactId=edge-matrix-sdk-java -Dversion=1.1-SNAPSHOT -Dpackaging=jar 26 | 27 | ```xml 28 | 29 | 30 | pro.edge-matrix 31 | edge-matrix-sdk-java 32 | 1.1-SNAPSHOT 33 | provided 34 | 35 | ``` 36 | 37 | ```xml 38 | 39 | 40 | org.junit.jupiter 41 | junit-jupiter 42 | 5.5.2 43 | test 44 | 45 | ``` 46 | 47 | ```xml 48 | 49 | 50 | org.web3j 51 | core 52 | 4.9.7 53 | 54 | ``` 55 | 56 | Sample code 57 | ----- 58 | 59 | ```java 60 | public class YourEdgeCaller { 61 | private static EdgeWeb3j web3j = EdgeWeb3j.build(new HttpService("https://oregon.edgematrix.xyz")); 62 | 63 | // A edge-matrix node that is running Stable Diffusion service for testing purpose. 64 | private static String TEST_PEERID = "16Uiu2HAm14xAsnJHDqnQNQ2Qqo1SapdRk9j8mBKY6mghVDP9B9u5"; 65 | 66 | public void sendRtcMessage() { 67 | EdgeService edgeService = new EdgeService(); 68 | String s = edgeService.sendRtcMsg( 69 | web3j, 70 | ChainId.TEST_NET.getId(), 71 | SampleKeys.CREDENTIALS, 72 | RtcMsg.createRtcMsg( 73 | "0x8eeb338239ada22d81ffb7adc995fe31a4d1dc2d701bc8a58fffe5b53e14281e", 74 | "edge_chat", 75 | "hello", 76 | new Address("0x0").toString())); 77 | System.out.println(s); 78 | } 79 | 80 | public void callStableDeffusionEdgeApi() { 81 | EdgeService edgeService = new EdgeService(); 82 | String peerId = TEST_PEERID; 83 | String apiHttpMethod = "POST"; 84 | String apiPath = "/sdapi/v1/txt2img"; 85 | String apiData = "{\n" + 86 | " \"enable_hr\": false,\n" + 87 | " \"denoising_strength\": 0,\n" + 88 | " \"firstphase_width\": 0,\n" + 89 | " \"firstphase_height\": 0,\n" + 90 | " \"hr_scale\": 2,\n" + 91 | " \"hr_upscaler\": \"\",\n" + 92 | " \"hr_second_pass_steps\": 0,\n" + 93 | " \"hr_resize_x\": 0,\n" + 94 | " \"hr_resize_y\": 0,\n" + 95 | " \"prompt\": \"white cat and dog\",\n" + 96 | " \"styles\": [\n" + 97 | " \"\"\n" + 98 | " ],\n" + 99 | " \"seed\": -1,\n" + 100 | " \"subseed\": -1,\n" + 101 | " \"subseed_strength\": 0,\n" + 102 | " \"seed_resize_from_h\": -1,\n" + 103 | " \"seed_resize_from_w\": -1,\n" + 104 | " \"sampler_name\": \"\",\n" + 105 | " \"batch_size\": 1,\n" + 106 | " \"n_iter\": 1,\n" + 107 | " \"steps\": 50,\n" + 108 | " \"cfg_scale\": 7,\n" + 109 | " \"width\": 512,\n" + 110 | " \"height\": 512,\n" + 111 | " \"restore_faces\": false,\n" + 112 | " \"tiling\": false,\n" + 113 | " \"do_not_save_samples\": false,\n" + 114 | " \"do_not_save_grid\": false,\n" + 115 | " \"negative_prompt\": \"\",\n" + 116 | " \"eta\": 0,\n" + 117 | " \"s_churn\": 0,\n" + 118 | " \"s_tmax\": 0,\n" + 119 | " \"s_tmin\": 0,\n" + 120 | " \"s_noise\": 1,\n" + 121 | " \"override_settings\": {},\n" + 122 | " \"override_settings_restore_afterwards\": true,\n" + 123 | " \"script_args\": [],\n" + 124 | " \"sampler_index\": \"Euler\",\n" + 125 | " \"script_name\": \"\",\n" + 126 | " \"send_images\": true,\n" + 127 | " \"save_images\": false,\n" + 128 | " \"alwayson_scripts\": {}\n" + 129 | " }"; 130 | String s = edgeService.callEdgeApi( 131 | web3j, 132 | ChainId.TEST_NET.getId(), 133 | edgeService.getNextTelegramNonce(web3j, SampleKeys.ADDRESS), 134 | SampleKeys.CREDENTIALS, 135 | peerId, 136 | apiHttpMethod, 137 | apiPath, 138 | apiData); 139 | if (isValidJSON(s)) { 140 | ObjectMapper objectMapper = new ObjectMapper(); 141 | EdgeCallResult edgeCallResult = objectMapper.readValue(s, EdgeCallResult.class); 142 | System.out.println("telegram_hash: " + edgeCallResult.getTelegram_hash()); 143 | System.out.println("response: " + new String(Base64.getDecoder().decode(edgeCallResult.getResponse()))); 144 | } else { 145 | System.out.println("invalid json"); 146 | } 147 | } 148 | } 149 | ``` 150 | 151 | License 152 | ------ 153 | Apache 2.0 154 | -------------------------------------------------------------------------------- /src/main/java/pro/edgematrix/crypto/type/Telegram.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Web3 Labs Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 5 | * the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on 10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the 11 | * specific language governing permissions and limitations under the License. 12 | */ 13 | package pro.edgematrix.crypto.type; 14 | 15 | import org.web3j.crypto.Sign; 16 | import org.web3j.crypto.transaction.type.LegacyTransaction; 17 | import org.web3j.crypto.transaction.type.TransactionType; 18 | import org.web3j.rlp.RlpString; 19 | import org.web3j.rlp.RlpType; 20 | import org.web3j.utils.Bytes; 21 | import org.web3j.utils.Numeric; 22 | 23 | import java.math.BigInteger; 24 | import java.util.ArrayList; 25 | import java.util.List; 26 | 27 | import static org.web3j.crypto.transaction.type.TransactionType.LEGACY; 28 | 29 | /** 30 | * Telegram class used for signing Telegram locally.
31 | * For the specification, refer to yellow 32 | * paper. 33 | */ 34 | public class Telegram implements ITelegram { 35 | 36 | private TransactionType type; 37 | private BigInteger nonce; 38 | private BigInteger gasPrice; 39 | private BigInteger gasLimit; 40 | private String to; 41 | private BigInteger value; 42 | private String data; 43 | 44 | public Telegram( 45 | BigInteger nonce, 46 | BigInteger gasPrice, 47 | BigInteger gasLimit, 48 | String to, 49 | BigInteger value, 50 | String data) { 51 | this(LEGACY, nonce, gasPrice, gasLimit, to, value, data); 52 | } 53 | 54 | // LegacyTransaction can have only one tx type. Use another constructor. 55 | @Deprecated 56 | public Telegram( 57 | TransactionType type, 58 | BigInteger nonce, 59 | BigInteger gasPrice, 60 | BigInteger gasLimit, 61 | String to, 62 | BigInteger value, 63 | String data) { 64 | this.type = type; 65 | this.nonce = nonce; 66 | this.gasPrice = gasPrice; 67 | this.gasLimit = gasLimit; 68 | this.to = to; 69 | this.value = value; 70 | this.data = data != null ? Numeric.cleanHexPrefix(data) : null; 71 | } 72 | 73 | @Override 74 | public List asRlpValues(Sign.SignatureData signatureData) { 75 | List result = new ArrayList<>(); 76 | 77 | result.add(RlpString.create(getNonce())); 78 | 79 | result.add(RlpString.create(getGasPrice())); 80 | result.add(RlpString.create(getGasLimit())); 81 | 82 | // an empty to address (contract creation) should not be encoded as a numeric 0 value 83 | String to = getTo(); 84 | if (to != null && to.length() > 0) { 85 | // addresses that start with zeros should be encoded with the zeros included, not 86 | // as numeric values 87 | result.add(RlpString.create(Numeric.hexStringToByteArray(to))); 88 | } else { 89 | result.add(RlpString.create("")); 90 | } 91 | 92 | result.add(RlpString.create(getValue())); 93 | 94 | // value field will already be hex encoded, so we need to convert into binary first 95 | byte[] data = Numeric.hexStringToByteArray(getData()); 96 | result.add(RlpString.create(data)); 97 | 98 | if (signatureData != null) { 99 | result.add(RlpString.create(Bytes.trimLeadingZeroes(signatureData.getV()))); 100 | result.add(RlpString.create(Bytes.trimLeadingZeroes(signatureData.getR()))); 101 | result.add(RlpString.create(Bytes.trimLeadingZeroes(signatureData.getS()))); 102 | } 103 | 104 | return result; 105 | } 106 | 107 | public static LegacyTransaction createContractTransaction( 108 | BigInteger nonce, 109 | BigInteger gasPrice, 110 | BigInteger gasLimit, 111 | BigInteger value, 112 | String init) { 113 | 114 | return new LegacyTransaction(nonce, gasPrice, gasLimit, "", value, init); 115 | } 116 | 117 | public static LegacyTransaction createEtherTransaction( 118 | BigInteger nonce, 119 | BigInteger gasPrice, 120 | BigInteger gasLimit, 121 | String to, 122 | BigInteger value) { 123 | 124 | return new LegacyTransaction(nonce, gasPrice, gasLimit, to, value, ""); 125 | } 126 | 127 | public static LegacyTransaction createTransaction( 128 | BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, String to, String data) { 129 | return createTransaction(nonce, gasPrice, gasLimit, to, BigInteger.ZERO, data); 130 | } 131 | 132 | public static LegacyTransaction createTransaction( 133 | BigInteger nonce, 134 | BigInteger gasPrice, 135 | BigInteger gasLimit, 136 | String to, 137 | BigInteger value, 138 | String data) { 139 | 140 | return new LegacyTransaction(nonce, gasPrice, gasLimit, to, value, data); 141 | } 142 | 143 | @Override 144 | public BigInteger getNonce() { 145 | return nonce; 146 | } 147 | 148 | @Override 149 | public BigInteger getGasPrice() { 150 | return gasPrice; 151 | } 152 | 153 | @Override 154 | public BigInteger getGasLimit() { 155 | return gasLimit; 156 | } 157 | 158 | @Override 159 | public String getTo() { 160 | return to; 161 | } 162 | 163 | @Override 164 | public BigInteger getValue() { 165 | return value; 166 | } 167 | 168 | @Override 169 | public String getData() { 170 | return data; 171 | } 172 | 173 | @Override 174 | public TransactionType getType() { 175 | return type; 176 | } 177 | } 178 | -------------------------------------------------------------------------------- /src/test/java/pro/edgematrix/crypto/TelegramEncoderTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 edgematrix Labs Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 5 | * the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on 10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the 11 | * specific language governing permissions and limitations under the License. 12 | */ 13 | package pro.edgematrix.crypto; 14 | 15 | import org.junit.jupiter.api.Test; 16 | import org.web3j.utils.Numeric; 17 | import pro.edgematrix.common.ChainId; 18 | import pro.edgematrix.common.PrecompileAddress; 19 | 20 | import java.math.BigInteger; 21 | 22 | import static org.junit.jupiter.api.Assertions.assertEquals; 23 | 24 | public class TelegramEncoderTest { 25 | 26 | @Test 27 | public void testSignMessageAfterEip155() { 28 | byte[] signedMessage = 29 | TelegramEncoder.signMessage( 30 | createEip155RawTransaction(), 31 | ChainId.TEST_NET.getId(), 32 | SampleKeys.CREDENTIALS); 33 | 34 | String hexMessage = Numeric.toHexString(signedMessage); 35 | String SIGN_RESULT_ETH_EXAMPLE = "0xf85d038080940000000000000000000000000000000000003101808028a0bec9c466527c5d86bba8f9df2c4db78fa19948ed9ff05de532b7607cff939474a0495b85bc7cc2bc8b69860f3033523afa3ef4f839cfc2687c0f4bbe60b718df5d"; 36 | assertEquals(SIGN_RESULT_ETH_EXAMPLE, hexMessage); 37 | } 38 | 39 | 40 | static RawTelegram createEip155RawTransaction() { 41 | return RawTelegram.createEtherTransaction( 42 | BigInteger.valueOf(3), 43 | BigInteger.valueOf(0), 44 | BigInteger.valueOf(0), 45 | PrecompileAddress.EDGE_RTC_SUBJECT.getAddress(), 46 | BigInteger.valueOf(0)); 47 | } 48 | 49 | @Test 50 | public void testSignTelegram() { 51 | byte[] signedMessage = 52 | TelegramEncoder.signMessage( 53 | createTestEdgeCallTelegram(), 54 | ChainId.TEST_NET.getId(), 55 | SampleKeys.CREDENTIALS); 56 | 57 | String hexMessage = Numeric.toHexString(signedMessage); 58 | System.out.println(hexMessage); 59 | String SIGN_RESULT_ETH_EXAMPLE = "0xf9054a14808094000000000000000000000000000000000000300180b904ec7b22706565724964223a2231365569753248416d31347841736e4a4844716e514e513251716f3153617064526b396a386d424b59366d67685644503942397535222c22656e64706f696e74223a222f617069222c22496e707574223a7b226d6574686f64223a2022504f5354222c2268656164657273223a5b5d2c2270617468223a222f73646170692f76312f74787432696d67222c22626f6479223a7b0a20202020202022656e61626c655f6872223a2066616c73652c0a2020202020202264656e6f6973696e675f737472656e677468223a20302c0a20202020202022666972737470686173655f7769647468223a20302c0a20202020202022666972737470686173655f686569676874223a20302c0a2020202020202268725f7363616c65223a20322c0a2020202020202268725f75707363616c6572223a2022222c0a2020202020202268725f7365636f6e645f706173735f7374657073223a20302c0a2020202020202268725f726573697a655f78223a20302c0a2020202020202268725f726573697a655f79223a20302c0a2020202020202270726f6d7074223a202277686974652063617420616e6420646f67222c0a202020202020227374796c6573223a205b0a202020202020202022220a2020202020205d2c0a2020202020202273656564223a202d312c0a2020202020202273756273656564223a202d312c0a20202020202022737562736565645f737472656e677468223a20302c0a20202020202022736565645f726573697a655f66726f6d5f68223a202d312c0a20202020202022736565645f726573697a655f66726f6d5f77223a202d312c0a2020202020202273616d706c65725f6e616d65223a2022222c0a2020202020202262617463685f73697a65223a20312c0a202020202020226e5f69746572223a20312c0a202020202020227374657073223a2035302c0a202020202020226366675f7363616c65223a20372c0a202020202020227769647468223a203531322c0a20202020202022686569676874223a203531322c0a20202020202022726573746f72655f6661636573223a2066616c73652c0a2020202020202274696c696e67223a2066616c73652c0a20202020202022646f5f6e6f745f736176655f73616d706c6573223a2066616c73652c0a20202020202022646f5f6e6f745f736176655f67726964223a2066616c73652c0a202020202020226e656761746976655f70726f6d7074223a2022222c0a20202020202022657461223a20302c0a20202020202022735f636875726e223a20302c0a20202020202022735f746d6178223a20302c0a20202020202022735f746d696e223a20302c0a20202020202022735f6e6f697365223a20312c0a202020202020226f766572726964655f73657474696e6773223a207b7d2c0a202020202020226f766572726964655f73657474696e67735f726573746f72655f61667465727761726473223a20747275652c0a202020202020227363726970745f61726773223a205b5d2c0a2020202020202273616d706c65725f696e646578223a202245756c6572222c0a202020202020227363726970745f6e616d65223a2022222c0a2020202020202273656e645f696d61676573223a20747275652c0a20202020202022736176655f696d61676573223a2066616c73652c0a20202020202022616c776179736f6e5f73637269707473223a207b7d0a202020207d7d7d28a04d738460dceedcd65074366c35c37e12fbe4e85f4b662fb306a61633cb1623d19f0cfc68b55ae48009ef981a6b2668cdc316466a7a82e181e4a3527a6b2036bd"; 60 | assertEquals(SIGN_RESULT_ETH_EXAMPLE, hexMessage); 61 | } 62 | 63 | 64 | static RawTelegram createTestEdgeCallTelegram() { 65 | return RawTelegram.createTransaction( 66 | BigInteger.valueOf(20), 67 | BigInteger.valueOf(0), 68 | BigInteger.valueOf(0), 69 | PrecompileAddress.EDGE_CALL.getAddress(), 70 | BigInteger.valueOf(0), 71 | "{\"peerId\":\"16Uiu2HAm14xAsnJHDqnQNQ2Qqo1SapdRk9j8mBKY6mghVDP9B9u5\",\"endpoint\":\"/api\",\"Input\":{\"method\": \"POST\",\"headers\":[],\"path\":\"/sdapi/v1/txt2img\",\"body\":{\n" + 72 | " \"enable_hr\": false,\n" + 73 | " \"denoising_strength\": 0,\n" + 74 | " \"firstphase_width\": 0,\n" + 75 | " \"firstphase_height\": 0,\n" + 76 | " \"hr_scale\": 2,\n" + 77 | " \"hr_upscaler\": \"\",\n" + 78 | " \"hr_second_pass_steps\": 0,\n" + 79 | " \"hr_resize_x\": 0,\n" + 80 | " \"hr_resize_y\": 0,\n" + 81 | " \"prompt\": \"white cat and dog\",\n" + 82 | " \"styles\": [\n" + 83 | " \"\"\n" + 84 | " ],\n" + 85 | " \"seed\": -1,\n" + 86 | " \"subseed\": -1,\n" + 87 | " \"subseed_strength\": 0,\n" + 88 | " \"seed_resize_from_h\": -1,\n" + 89 | " \"seed_resize_from_w\": -1,\n" + 90 | " \"sampler_name\": \"\",\n" + 91 | " \"batch_size\": 1,\n" + 92 | " \"n_iter\": 1,\n" + 93 | " \"steps\": 50,\n" + 94 | " \"cfg_scale\": 7,\n" + 95 | " \"width\": 512,\n" + 96 | " \"height\": 512,\n" + 97 | " \"restore_faces\": false,\n" + 98 | " \"tiling\": false,\n" + 99 | " \"do_not_save_samples\": false,\n" + 100 | " \"do_not_save_grid\": false,\n" + 101 | " \"negative_prompt\": \"\",\n" + 102 | " \"eta\": 0,\n" + 103 | " \"s_churn\": 0,\n" + 104 | " \"s_tmax\": 0,\n" + 105 | " \"s_tmin\": 0,\n" + 106 | " \"s_noise\": 1,\n" + 107 | " \"override_settings\": {},\n" + 108 | " \"override_settings_restore_afterwards\": true,\n" + 109 | " \"script_args\": [],\n" + 110 | " \"sampler_index\": \"Euler\",\n" + 111 | " \"script_name\": \"\",\n" + 112 | " \"send_images\": true,\n" + 113 | " \"save_images\": false,\n" + 114 | " \"alwayson_scripts\": {}\n" + 115 | " }}}"); 116 | } 117 | 118 | } 119 | -------------------------------------------------------------------------------- /src/main/java/pro/edgematrix/EdgeService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 edgematrix Labs Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 5 | * the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on 10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the 11 | * specific language governing permissions and limitations under the License. 12 | */ 13 | package pro.edgematrix; 14 | 15 | import org.web3j.crypto.Credentials; 16 | import org.web3j.protocol.core.DefaultBlockParameterName; 17 | import org.web3j.protocol.core.Request; 18 | import org.web3j.protocol.core.methods.response.EthGetTransactionCount; 19 | import org.web3j.protocol.core.methods.response.EthGetTransactionReceipt; 20 | import org.web3j.protocol.core.methods.response.TransactionReceipt; 21 | import org.web3j.utils.Numeric; 22 | import pro.edgematrix.common.PrecompileAddress; 23 | import pro.edgematrix.crypto.RawRtcMsg; 24 | import pro.edgematrix.crypto.RawTelegram; 25 | import pro.edgematrix.crypto.RtcMsgEncoder; 26 | import pro.edgematrix.crypto.TelegramEncoder; 27 | import pro.edgematrix.protocol.methods.response.EdgeSendRtcMsg; 28 | import pro.edgematrix.protocol.methods.response.EdgeSendTelegram; 29 | 30 | import java.io.IOException; 31 | import java.math.BigInteger; 32 | import java.util.concurrent.ExecutionException; 33 | 34 | /** 35 | * JSON-RPC Request service. 36 | */ 37 | public class EdgeService { 38 | /** 39 | * send a telegram to edge-matrix node 40 | * 41 | * @param web3j EdgeWeb3j instance 42 | * @param chainId EMC chain id, 2 is testnet chain id 43 | * @param nonce nonce for caller 44 | * @param contractAddress address to 45 | * @param credentials caller's credential 46 | * @param data data for call, "" is empty data 47 | * @return deserialized JSON-RPC responses 48 | */ 49 | public String sendTelegram(EdgeWeb3j web3j, long chainId, BigInteger nonce, String contractAddress, Credentials credentials, String data) { 50 | if (web3j == null) return null; 51 | 52 | BigInteger gasPrice = BigInteger.valueOf(0); 53 | BigInteger gasLimit = BigInteger.valueOf(0); 54 | BigInteger value = BigInteger.valueOf(0); 55 | RawTelegram rawTransaction = RawTelegram.createTransaction(nonce, gasPrice, gasLimit, contractAddress, value, data); 56 | 57 | byte[] signMessage = TelegramEncoder.signMessage(rawTransaction, chainId, credentials); 58 | String signData = Numeric.toHexString(signMessage); 59 | 60 | if (!"".equals(signData)) { 61 | try { 62 | EdgeSendTelegram send = web3j.edgeSendRawTelegram(signData).send(); 63 | if (send.hasError()) { 64 | throw new RuntimeException(send.getError().getMessage()); 65 | } else { 66 | return send.getResult(); 67 | } 68 | } catch (IOException e) { 69 | throw new RuntimeException("send telegram exception"); 70 | } 71 | } 72 | return null; 73 | } 74 | 75 | /** 76 | * create a rtc subject on edge-matrix net 77 | * 78 | * @param web3j EdgeWeb3j instance 79 | * @param chainId EMC chain id, 2 is testnet chain id 80 | * @param nonce nonce for caller 81 | * @param credentials caller's credential 82 | * @return deserialized JSON-RPC responses 83 | */ 84 | public String createRtcSubject(EdgeWeb3j web3j, long chainId, BigInteger nonce, Credentials credentials) { 85 | if (web3j == null) return null; 86 | 87 | BigInteger gasPrice = BigInteger.valueOf(0); 88 | BigInteger gasLimit = BigInteger.valueOf(0); 89 | BigInteger value = BigInteger.valueOf(0); 90 | RawTelegram rawTransaction = RawTelegram.createTransaction(nonce, gasPrice, gasLimit, PrecompileAddress.EDGE_RTC_SUBJECT.getAddress(), value, ""); 91 | 92 | byte[] signMessage = TelegramEncoder.signMessage(rawTransaction, chainId, credentials); 93 | String signData = Numeric.toHexString(signMessage); 94 | 95 | if (!"".equals(signData)) { 96 | try { 97 | EdgeSendTelegram send = web3j.edgeSendRawTelegram(signData).send(); 98 | if (send.hasError()) { 99 | throw new RuntimeException(send.getError().getMessage()); 100 | } else { 101 | return send.getResult(); 102 | } 103 | } catch (IOException e) { 104 | throw new RuntimeException("send telegram exception"); 105 | } 106 | } 107 | return null; 108 | } 109 | 110 | public String callEdgeApi(EdgeWeb3j web3j, long chainId, BigInteger nonce, Credentials credentials, String peerId, String apiHttpMethod, String apiPath, String apiData) { 111 | if (web3j == null) return null; 112 | 113 | BigInteger gasPrice = BigInteger.valueOf(0); 114 | BigInteger gasLimit = BigInteger.valueOf(0); 115 | BigInteger value = BigInteger.valueOf(0); 116 | String data = String.format("{\"peerId\":\"%s\",\"endpoint\":\"/api\",\"Input\":{\"method\": \"%s\",\"headers\":[],\"path\":\"%s\",\"body\":%s}}",peerId,apiHttpMethod,apiPath,apiData); 117 | RawTelegram rawTransaction = RawTelegram.createTransaction(nonce, gasPrice, gasLimit, PrecompileAddress.EDGE_CALL.getAddress(), value, data); 118 | 119 | byte[] signMessage = TelegramEncoder.signMessage(rawTransaction, chainId, credentials); 120 | String signData = Numeric.toHexString(signMessage); 121 | 122 | if (!"".equals(signData)) { 123 | try { 124 | Request edgeSendTelegramRequest = web3j.edgeSendRawTelegram(signData); 125 | EdgeSendTelegram send = edgeSendTelegramRequest.send(); 126 | if (send.hasError()) { 127 | throw new RuntimeException(send.getError().getMessage()); 128 | } else { 129 | return send.getResult(); 130 | } 131 | } catch (IOException e) { 132 | throw new RuntimeException("send telegram exception"); 133 | } 134 | } 135 | return null; 136 | } 137 | 138 | /** 139 | * send a message to rtc subject 140 | * 141 | * @param web3j EdgeWeb3j instance 142 | * @param chainId EMC chain id, 2 is testnet chain id 143 | * @param credentials caller's credential 144 | * @param rtcMsg RtcMsg instance to be sent 145 | * @return deserialized JSON-RPC responses 146 | */ 147 | public String sendRtcMsg(EdgeWeb3j web3j, long chainId, Credentials credentials, RtcMsg rtcMsg) { 148 | if (web3j == null) return null; 149 | 150 | RawRtcMsg rawTransaction = RawRtcMsg.createRtcMsg(rtcMsg.getSubject(), rtcMsg.getApplication(), rtcMsg.getContent(), rtcMsg.getTo()); 151 | 152 | byte[] signMessage = RtcMsgEncoder.signMessage(rawTransaction, chainId, credentials); 153 | String signData = Numeric.toHexString(signMessage); 154 | 155 | if (!"".equals(signData)) { 156 | try { 157 | EdgeSendRtcMsg send = web3j.edgeSendRawMsg(signData).send(); 158 | if (send.hasError()) { 159 | throw new RuntimeException(send.getError().getMessage()); 160 | } else { 161 | return send.getResult(); 162 | } 163 | } catch (IOException e) { 164 | throw new RuntimeException("send rtcMsg exception"); 165 | } 166 | } 167 | return null; 168 | } 169 | 170 | /** 171 | * get next nonce for caller 172 | * 173 | * @param web3j EdgeWeb3j instance 174 | * @param address caller's address - e.g. "0x0aF137aa3EcC7d10d926013ee34049AfA77382e6" 175 | * @return number of nonce, will be used for sendTelegram 176 | * @throws ExecutionException ExecutionException 177 | * @throws InterruptedException InterruptedException 178 | */ 179 | public BigInteger getNextTelegramNonce(EdgeWeb3j web3j, String address) throws ExecutionException, InterruptedException { 180 | if (web3j == null) return null; 181 | 182 | EthGetTransactionCount ethGetTransactionCount = web3j.edgeGetTelegramCount( 183 | address, DefaultBlockParameterName.LATEST).sendAsync().get(); 184 | if (ethGetTransactionCount != null) { 185 | return ethGetTransactionCount.getTransactionCount(); 186 | } 187 | return null; 188 | } 189 | 190 | /** 191 | * get a receipt of sendTelegram call 192 | * 193 | * @param web3j EdgeWeb3j instance 194 | * @param telegramHash hashString returned by a sendTelegram call, - e.g. "0x6b7c880d58fef940e7b7932b9239d2737b4a71583c4640757e234de94bb98c0b" 195 | * @return EthGetTransactionReceipt 196 | * @throws IOException IOException 197 | */ 198 | public TransactionReceipt getTelegramReceipt(EdgeWeb3j web3j, String telegramHash) throws IOException { 199 | EthGetTransactionReceipt transactionReceipt = web3j.edgeGetTelegramReceipt(telegramHash).send(); 200 | if (transactionReceipt != null && transactionReceipt.getTransactionReceipt().isPresent()) { 201 | return transactionReceipt.getTransactionReceipt().get(); 202 | } else { 203 | return null; 204 | } 205 | } 206 | } 207 | -------------------------------------------------------------------------------- /src/test/java/pro/edgematrix/crypto/EdgeServiceTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 edgematrix Labs Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 5 | * the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on 10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the 11 | * specific language governing permissions and limitations under the License. 12 | */ 13 | package pro.edgematrix.crypto; 14 | 15 | import com.fasterxml.jackson.core.JsonParseException; 16 | import com.fasterxml.jackson.core.JsonParser; 17 | import com.fasterxml.jackson.core.JsonProcessingException; 18 | import com.fasterxml.jackson.databind.ObjectMapper; 19 | import okhttp3.OkHttpClient; 20 | import org.junit.jupiter.api.AfterAll; 21 | import org.junit.jupiter.api.BeforeAll; 22 | import org.junit.jupiter.api.Test; 23 | import org.web3j.abi.datatypes.Address; 24 | import org.web3j.protocol.core.methods.response.TransactionReceipt; 25 | import org.web3j.protocol.http.HttpService; 26 | import pro.edgematrix.EdgeService; 27 | import pro.edgematrix.EdgeWeb3j; 28 | import pro.edgematrix.RtcMsg; 29 | import pro.edgematrix.common.ChainId; 30 | import pro.edgematrix.common.PrecompileAddress; 31 | import pro.edgematrix.protocol.methods.response.EdgeCallResult; 32 | 33 | import java.io.IOException; 34 | import java.math.BigInteger; 35 | import java.util.Base64; 36 | import java.util.concurrent.ExecutionException; 37 | import java.util.concurrent.TimeUnit; 38 | 39 | public class EdgeServiceTest { 40 | 41 | /** 42 | * "oregon.edgematrix.xyz" is one of testnet node's rpcUrl 43 | */ 44 | private static EdgeWeb3j web3j = null; 45 | static { 46 | OkHttpClient httpClient = new OkHttpClient.Builder() 47 | .retryOnConnectionFailure(true) 48 | .connectTimeout(30, TimeUnit.SECONDS) 49 | .readTimeout(30, TimeUnit.SECONDS) 50 | .writeTimeout(30, TimeUnit.SECONDS) 51 | .build(); 52 | web3j = EdgeWeb3j.build(new HttpService("https://oregon.edgematrix.xyz",httpClient)); 53 | } 54 | 55 | // A edge-matrix node that is running Stable Diffusion service for testing purpose. 56 | private final static String TEST_PEERID = "16Uiu2HAmHsjCvAAVmWUUKt6WA85gHUEnepa6xzNqvAeC8gA4AWUC"; 57 | 58 | 59 | @BeforeAll 60 | public static void prepare() { 61 | } 62 | 63 | @AfterAll 64 | public static void finish() { 65 | web3j.shutdown(); 66 | } 67 | 68 | /** 69 | * Test for send a telegram to a precompile contract with data 70 | * 71 | * @throws ExecutionException 72 | * @throws InterruptedException 73 | */ 74 | @Test 75 | public void testSendTelegram() throws ExecutionException, InterruptedException { 76 | EdgeService edgeService = new EdgeService(); 77 | String s = edgeService.sendTelegram( 78 | web3j, 79 | ChainId.TEST_NET.getId(), 80 | edgeService.getNextTelegramNonce(web3j, SampleKeys.ADDRESS), 81 | PrecompileAddress.EDGE_RTC_SUBJECT.getAddress(), 82 | SampleKeys.CREDENTIALS, 83 | ""); 84 | System.out.println(s); 85 | } 86 | 87 | /** 88 | * Test for create a rtc chat channel 89 | * 90 | * @throws ExecutionException 91 | * @throws InterruptedException 92 | */ 93 | @Test 94 | public void testCreateRtcSubject() throws ExecutionException, InterruptedException { 95 | EdgeService edgeService = new EdgeService(); 96 | String s = edgeService.createRtcSubject( 97 | web3j, 98 | ChainId.TEST_NET.getId(), 99 | edgeService.getNextTelegramNonce(web3j, SampleKeys.ADDRESS), 100 | SampleKeys.CREDENTIALS); 101 | // returen a rtc subject hash as rtc channel hash 102 | System.out.println(s); 103 | } 104 | 105 | /** 106 | * Test for a Stable Diffusion txt2img api call 107 | * 108 | * @throws ExecutionException 109 | * @throws InterruptedException 110 | */ 111 | @Test 112 | public void testCallEdgeApi() throws ExecutionException, InterruptedException, JsonProcessingException { 113 | EdgeService edgeService = new EdgeService(); 114 | String peerId = TEST_PEERID; 115 | String apiHttpMethod = "POST"; 116 | String apiPath = "/sdapi/v1/txt2img"; 117 | String apiData = "{\n" + 118 | " \"enable_hr\": false,\n" + 119 | " \"denoising_strength\": 0,\n" + 120 | " \"firstphase_width\": 0,\n" + 121 | " \"firstphase_height\": 0,\n" + 122 | " \"hr_scale\": 2,\n" + 123 | " \"hr_upscaler\": \"\",\n" + 124 | " \"hr_second_pass_steps\": 0,\n" + 125 | " \"hr_resize_x\": 0,\n" + 126 | " \"hr_resize_y\": 0,\n" + 127 | " \"prompt\": \"white cat and dog\",\n" + 128 | " \"styles\": [\n" + 129 | " \"\"\n" + 130 | " ],\n" + 131 | " \"seed\": -1,\n" + 132 | " \"subseed\": -1,\n" + 133 | " \"subseed_strength\": 0,\n" + 134 | " \"seed_resize_from_h\": -1,\n" + 135 | " \"seed_resize_from_w\": -1,\n" + 136 | " \"sampler_name\": \"\",\n" + 137 | " \"batch_size\": 1,\n" + 138 | " \"n_iter\": 1,\n" + 139 | " \"steps\": 50,\n" + 140 | " \"cfg_scale\": 7,\n" + 141 | " \"width\": 512,\n" + 142 | " \"height\": 512,\n" + 143 | " \"restore_faces\": false,\n" + 144 | " \"tiling\": false,\n" + 145 | " \"do_not_save_samples\": false,\n" + 146 | " \"do_not_save_grid\": false,\n" + 147 | " \"negative_prompt\": \"\",\n" + 148 | " \"eta\": 0,\n" + 149 | " \"s_churn\": 0,\n" + 150 | " \"s_tmax\": 0,\n" + 151 | " \"s_tmin\": 0,\n" + 152 | " \"s_noise\": 1,\n" + 153 | " \"override_settings\": {},\n" + 154 | " \"override_settings_restore_afterwards\": true,\n" + 155 | " \"script_args\": [],\n" + 156 | " \"sampler_index\": \"Euler\",\n" + 157 | " \"script_name\": \"\",\n" + 158 | " \"send_images\": true,\n" + 159 | " \"save_images\": false,\n" + 160 | " \"alwayson_scripts\": {}\n" + 161 | " }"; 162 | String s = edgeService.callEdgeApi( 163 | web3j, 164 | ChainId.TEST_NET.getId(), 165 | edgeService.getNextTelegramNonce(web3j, SampleKeys.ADDRESS), 166 | SampleKeys.CREDENTIALS, 167 | peerId, 168 | apiHttpMethod, 169 | apiPath, 170 | "{\"prompt\":\"(Raw photo,realistic,photorealistic),dynamic angle,gorgeous,amazing,epic,ultra-detailed,1girl\\\\(mecha\\\\),(techpunkmask:1.2),slim body,kong-fu,black hair,black eyes,Chinese hairstyle,see-through,glowing body,cyberpunk,cyborg ninja,cinematic Lighting,Accent Lighting,dramatic_shadow,ray_tracing,complex clothes and patterns, fighting,(holding laser-katana:1.3),hair-bangs,red long scarf,highly real skin,outdoors, strong dynamic pose, neon lights, beautiful glowing,\",\"negative_prompt\":\"(nsfw,nude,loli,children,childish,child, EasyNegative)\",\"sampler\":\"Euler a\",\"steps\":40,\"width\":256,\"height\":256,\"cfg_scale\":7,\"seed\":1405709391,\"clip_skip\":2}"); 171 | if (isValidJSON(s)) { 172 | ObjectMapper objectMapper = new ObjectMapper(); 173 | EdgeCallResult edgeCallResult = objectMapper.readValue(s, EdgeCallResult.class); 174 | System.out.println("telegram_hash: " + edgeCallResult.getTelegram_hash()); 175 | System.out.println("response: " + new String(Base64.getDecoder().decode(edgeCallResult.getResponse()))); 176 | } else { 177 | System.out.println("invalid json"); 178 | } 179 | } 180 | 181 | public boolean isValidJSON(final String json) { 182 | boolean valid = false; 183 | try { 184 | final JsonParser parser = new ObjectMapper().createParser(json); 185 | while (parser.nextToken() != null) { 186 | } 187 | valid = true; 188 | } catch (JsonParseException jpe) { 189 | } catch (IOException ioe) { 190 | ioe.printStackTrace(); 191 | } 192 | return valid; 193 | } 194 | 195 | /** 196 | * send a broadcast rtc msg to a rtc channel 197 | */ 198 | @Test 199 | public void testSendRtcMsg() { 200 | EdgeService edgeService = new EdgeService(); 201 | String s = edgeService.sendRtcMsg( 202 | web3j, 203 | ChainId.TEST_NET.getId(), 204 | SampleKeys.CREDENTIALS, 205 | RtcMsg.createRtcMsg( 206 | "0x8eeb338239ada22d81ffb7adc995fe31a4d1dc2d701bc8a58fffe5b53e14281e", 207 | "edge_chat", 208 | "hello", 209 | new Address("0x0").toString())); 210 | System.out.println(s); 211 | } 212 | 213 | @Test 214 | public void testGetNextTelegramNonce() throws ExecutionException, InterruptedException { 215 | EdgeService edgeService = new EdgeService(); 216 | BigInteger telegramCount = edgeService.getNextTelegramNonce(web3j, SampleKeys.ADDRESS); 217 | if (telegramCount != null) { 218 | System.out.printf("nextNonce: %s%n", telegramCount); 219 | } 220 | } 221 | 222 | @Test 223 | public void testGetTelegramReceipt() throws IOException { 224 | EdgeService edgeService = new EdgeService(); 225 | TransactionReceipt receipt = edgeService.getTelegramReceipt(web3j, "0x6b7c880d58fef940e7b7932b9239d2737b4a71583c4640757e234de94bb98c0b"); 226 | if (receipt != null && receipt.getBlockHash() != null && receipt.getStatus() != null && receipt.getTo() != null) { 227 | System.out.printf("blockHash: %s, status: %s, to: %s%n", receipt.getBlockHash(), receipt.getStatus(), receipt.getTo()); 228 | } 229 | } 230 | 231 | } 232 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/main/java/pro/edgematrix/crypto/Sign.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 edgematrix Labs Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 5 | * the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on 10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the 11 | * specific language governing permissions and limitations under the License. 12 | */ 13 | package pro.edgematrix.crypto; 14 | 15 | import org.bouncycastle.asn1.x9.X9ECParameters; 16 | import org.bouncycastle.asn1.x9.X9IntegerConverter; 17 | import org.bouncycastle.crypto.ec.CustomNamedCurves; 18 | import org.bouncycastle.crypto.params.ECDomainParameters; 19 | import org.bouncycastle.math.ec.ECAlgorithms; 20 | import org.bouncycastle.math.ec.ECPoint; 21 | import org.bouncycastle.math.ec.FixedPointCombMultiplier; 22 | import org.bouncycastle.math.ec.custom.sec.SecP256K1Curve; 23 | import org.web3j.crypto.ECDSASignature; 24 | import org.web3j.crypto.ECKeyPair; 25 | import org.web3j.crypto.Hash; 26 | import org.web3j.crypto.StructuredDataEncoder; 27 | import org.web3j.utils.Numeric; 28 | 29 | import java.io.IOException; 30 | import java.math.BigInteger; 31 | import java.nio.charset.StandardCharsets; 32 | import java.security.SignatureException; 33 | import java.util.Arrays; 34 | 35 | import static org.bouncycastle.util.BigIntegers.TWO; 36 | import static org.web3j.utils.Assertions.verifyPrecondition; 37 | 38 | /** 39 | * Transaction signing logic. 40 | * 41 | *

Adapted from the 43 | * BitcoinJ ECKey implementation. 44 | */ 45 | public class Sign { 46 | 47 | public static final X9ECParameters CURVE_PARAMS = CustomNamedCurves.getByName("secp256k1"); 48 | public static final int CHAIN_ID_INC = 35; 49 | public static final int LOWER_REAL_V = 27; 50 | // The v signature parameter starts at 37 because 1 is the first valid chainId so: 51 | // chainId >= 1 implies that 2 * chainId + CHAIN_ID_INC >= 37. 52 | // https://eips.ethereum.org/EIPS/eip-155 53 | public static final int REPLAY_PROTECTED_V_MIN = 37; 54 | static final ECDomainParameters CURVE = 55 | new ECDomainParameters( 56 | CURVE_PARAMS.getCurve(), 57 | CURVE_PARAMS.getG(), 58 | CURVE_PARAMS.getN(), 59 | CURVE_PARAMS.getH()); 60 | static final BigInteger HALF_CURVE_ORDER = CURVE_PARAMS.getN().shiftRight(1); 61 | 62 | static final String MESSAGE_PREFIX = "\u0019Ethereum Signed Message:\n"; 63 | 64 | static byte[] getEthereumMessagePrefix(int messageLength) { 65 | return MESSAGE_PREFIX 66 | .concat(String.valueOf(messageLength)) 67 | .getBytes(StandardCharsets.UTF_8); 68 | } 69 | 70 | public static byte[] getEthereumMessageHash(byte[] message) { 71 | byte[] prefix = getEthereumMessagePrefix(message.length); 72 | 73 | byte[] result = new byte[prefix.length + message.length]; 74 | System.arraycopy(prefix, 0, result, 0, prefix.length); 75 | System.arraycopy(message, 0, result, prefix.length, message.length); 76 | 77 | return Hash.sha3(result); 78 | } 79 | 80 | public static SignatureData signPrefixedMessage(byte[] message, ECKeyPair keyPair) { 81 | return signMessage(getEthereumMessageHash(message), keyPair, false); 82 | } 83 | 84 | public static SignatureData signMessage(byte[] message, ECKeyPair keyPair) { 85 | return signMessage(message, keyPair, true); 86 | } 87 | 88 | public static SignatureData signTypedData(String jsonData, ECKeyPair keyPair) 89 | throws IOException { 90 | StructuredDataEncoder dataEncoder = new StructuredDataEncoder(jsonData); 91 | byte[] hashStructuredData = dataEncoder.hashStructuredData(); 92 | 93 | return signMessage(hashStructuredData, keyPair, false); 94 | } 95 | 96 | public static SignatureData signMessage(byte[] message, ECKeyPair keyPair, boolean needToHash) { 97 | BigInteger publicKey = keyPair.getPublicKey(); 98 | byte[] messageHash; 99 | if (needToHash) { 100 | messageHash = Hash.sha3(message); 101 | } else { 102 | messageHash = message; 103 | } 104 | 105 | ECDSASignature sig = keyPair.sign(messageHash); 106 | 107 | return createSignatureData(sig, publicKey, messageHash); 108 | } 109 | 110 | /** 111 | * Signature without EIP-155 (Simple replay attack protection) 112 | * https://eips.ethereum.org/EIPS/eip-155 To add EIP-155 call 113 | * TransactionEncoder.createEip155SignatureData after that. 114 | */ 115 | public static SignatureData createSignatureData( 116 | ECDSASignature sig, BigInteger publicKey, byte[] messageHash) { 117 | // Now we have to work backwards to figure out the recId needed to recover the signature. 118 | int recId = -1; 119 | for (int i = 0; i < 4; i++) { 120 | BigInteger k = recoverFromSignature(i, sig, messageHash); 121 | if (k != null && k.equals(publicKey)) { 122 | recId = i; 123 | break; 124 | } 125 | } 126 | if (recId == -1) { 127 | throw new RuntimeException( 128 | "Could not construct a recoverable key. Are your credentials valid?"); 129 | } 130 | 131 | int headerByte = recId + 27; 132 | 133 | // 1 header + 32 bytes for R + 32 bytes for S 134 | byte[] v = new byte[] {(byte) headerByte}; 135 | byte[] r = Numeric.toBytesPadded(sig.r, 32); 136 | byte[] s = Numeric.toBytesPadded(sig.s, 32); 137 | 138 | return new SignatureData(v, r, s); 139 | } 140 | 141 | /** 142 | * Given the components of a signature and a selector value, recover and return the public key 143 | * that generated the signature according to the algorithm in SEC1v2 section 4.1.6. 144 | * 145 | *

The recId is an index from 0 to 3 which indicates which of the 4 possible keys is the 146 | * correct one. Because the key recovery operation yields multiple potential keys, the correct 147 | * key must either be stored alongside the signature, or you must be willing to try each recId 148 | * in turn until you find one that outputs the key you are expecting. 149 | * 150 | *

If this method returns null it means recovery was not possible and recId should be 151 | * iterated. 152 | * 153 | *

Given the above two points, a correct usage of this method is inside a for loop from 0 to 154 | * 3, and if the output is null OR a key that is not the one you expect, you try again with the 155 | * next recId. 156 | * 157 | * @param recId Which possible key to recover. 158 | * @param sig the R and S components of the signature, wrapped. 159 | * @param message Hash of the data that was signed. 160 | * @return An ECKey containing only the public part, or null if recovery wasn't possible. 161 | */ 162 | public static BigInteger recoverFromSignature(int recId, ECDSASignature sig, byte[] message) { 163 | verifyPrecondition(recId >= 0 && recId <= 3, "recId must be in the range of [0, 3]"); 164 | verifyPrecondition(sig.r.signum() >= 0, "r must be positive"); 165 | verifyPrecondition(sig.s.signum() >= 0, "s must be positive"); 166 | verifyPrecondition(message != null, "message cannot be null"); 167 | 168 | // 1.0 For j from 0 to h (h == recId here and the loop is outside this function) 169 | // 1.1 Let x = r + jn 170 | BigInteger n = CURVE.getN(); // Curve order. 171 | BigInteger i = BigInteger.valueOf((long) recId / 2); 172 | BigInteger x = sig.r.add(i.multiply(n)); 173 | // 1.2. Convert the integer x to an octet string X of length mlen using the conversion 174 | // routine specified in Section 2.3.7, where mlen = ⌈(log2 p)/8⌉ or mlen = ⌈m/8⌉. 175 | // 1.3. Convert the octet string (16 set binary digits)||X to an elliptic curve point R 176 | // using the conversion routine specified in Section 2.3.4. If this conversion 177 | // routine outputs "invalid", then do another iteration of Step 1. 178 | // 179 | // More concisely, what these points mean is to use X as a compressed public key. 180 | BigInteger prime = SecP256K1Curve.q; 181 | if (x.compareTo(prime) >= 0) { 182 | // Cannot have point co-ordinates larger than this as everything takes place modulo Q. 183 | return null; 184 | } 185 | // Compressed keys require you to know an extra bit of data about the y-coord as there are 186 | // two possibilities. So it's encoded in the recId. 187 | ECPoint R = decompressKey(x, (recId & 1) == 1); 188 | // 1.4. If nR != point at infinity, then do another iteration of Step 1 (callers 189 | // responsibility). 190 | if (!R.multiply(n).isInfinity()) { 191 | return null; 192 | } 193 | // 1.5. Compute e from M using Steps 2 and 3 of ECDSA signature verification. 194 | BigInteger e = new BigInteger(1, message); 195 | // 1.6. For k from 1 to 2 do the following. (loop is outside this function via 196 | // iterating recId) 197 | // 1.6.1. Compute a candidate public key as: 198 | // Q = mi(r) * (sR - eG) 199 | // 200 | // Where mi(x) is the modular multiplicative inverse. We transform this into the following: 201 | // Q = (mi(r) * s ** R) + (mi(r) * -e ** G) 202 | // Where -e is the modular additive inverse of e, that is z such that z + e = 0 (mod n). 203 | // In the above equation ** is point multiplication and + is point addition (the EC group 204 | // operator). 205 | // 206 | // We can find the additive inverse by subtracting e from zero then taking the mod. For 207 | // example the additive inverse of 3 modulo 11 is 8 because 3 + 8 mod 11 = 0, and 208 | // -3 mod 11 = 8. 209 | BigInteger eInv = BigInteger.ZERO.subtract(e).mod(n); 210 | BigInteger rInv = sig.r.modInverse(n); 211 | BigInteger srInv = rInv.multiply(sig.s).mod(n); 212 | BigInteger eInvrInv = rInv.multiply(eInv).mod(n); 213 | ECPoint q = ECAlgorithms.sumOfTwoMultiplies(CURVE.getG(), eInvrInv, R, srInv); 214 | 215 | byte[] qBytes = q.getEncoded(false); 216 | // We remove the prefix 217 | return new BigInteger(1, Arrays.copyOfRange(qBytes, 1, qBytes.length)); 218 | } 219 | 220 | /** Decompress a compressed public key (x co-ord and low-bit of y-coord). */ 221 | private static ECPoint decompressKey(BigInteger xBN, boolean yBit) { 222 | X9IntegerConverter x9 = new X9IntegerConverter(); 223 | byte[] compEnc = x9.integerToBytes(xBN, 1 + x9.getByteLength(CURVE.getCurve())); 224 | compEnc[0] = (byte) (yBit ? 0x03 : 0x02); 225 | return CURVE.getCurve().decodePoint(compEnc); 226 | } 227 | 228 | /** 229 | * Given an arbitrary piece of text and an Ethereum message signature encoded in bytes, returns 230 | * the public key that was used to sign it. This can then be compared to the expected public key 231 | * to determine if the signature was correct. 232 | * 233 | * @param message RLP encoded message. 234 | * @param signatureData The message signature components 235 | * @return the public key used to sign the message 236 | * @throws SignatureException If the public key could not be recovered or if there was a 237 | * signature format error. 238 | */ 239 | public static BigInteger signedMessageToKey(byte[] message, SignatureData signatureData) 240 | throws SignatureException { 241 | return signedMessageHashToKey(Hash.sha3(message), signatureData); 242 | } 243 | 244 | /** 245 | * Given an arbitrary message and an Ethereum message signature encoded in bytes, returns the 246 | * public key that was used to sign it. This can then be compared to the expected public key to 247 | * determine if the signature was correct. 248 | * 249 | * @param message The message. 250 | * @param signatureData The message signature components 251 | * @return the public key used to sign the message 252 | * @throws SignatureException If the public key could not be recovered or if there was a 253 | * signature format error. 254 | */ 255 | public static BigInteger signedPrefixedMessageToKey(byte[] message, SignatureData signatureData) 256 | throws SignatureException { 257 | return signedMessageHashToKey(getEthereumMessageHash(message), signatureData); 258 | } 259 | 260 | /** 261 | * Given an arbitrary message hash and an Ethereum message signature encoded in bytes, returns 262 | * the public key that was used to sign it. This can then be compared to the expected public key 263 | * to determine if the signature was correct. 264 | * 265 | * @param messageHash The message hash. 266 | * @param signatureData The message signature components 267 | * @return the public key used to sign the message 268 | * @throws SignatureException If the public key could not be recovered or if there was a 269 | * signature format error. 270 | */ 271 | public static BigInteger signedMessageHashToKey(byte[] messageHash, SignatureData signatureData) 272 | throws SignatureException { 273 | 274 | byte[] r = signatureData.getR(); 275 | byte[] s = signatureData.getS(); 276 | verifyPrecondition(r != null && r.length == 32, "r must be 32 bytes"); 277 | verifyPrecondition(s != null && s.length == 32, "s must be 32 bytes"); 278 | 279 | int header = signatureData.getV()[0] & 0xFF; 280 | // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y, 281 | // 0x1D = second key with even y, 0x1E = second key with odd y 282 | if (header < 27 || header > 34) { 283 | throw new SignatureException("Header byte out of range: " + header); 284 | } 285 | 286 | ECDSASignature sig = 287 | new ECDSASignature( 288 | new BigInteger(1, signatureData.getR()), 289 | new BigInteger(1, signatureData.getS())); 290 | 291 | int recId = header - 27; 292 | BigInteger key = recoverFromSignature(recId, sig, messageHash); 293 | if (key == null) { 294 | throw new SignatureException("Could not recover public key from signature"); 295 | } 296 | return key; 297 | } 298 | 299 | /** 300 | * Returns recovery ID. 301 | * 302 | * @param signatureData The message signature components 303 | * @param chainId of the network 304 | * @return int recovery ID 305 | */ 306 | public static int getRecId(SignatureData signatureData, long chainId) { 307 | BigInteger v = Numeric.toBigInt(signatureData.getV()); 308 | BigInteger lowerRealV = BigInteger.valueOf(LOWER_REAL_V); 309 | BigInteger lowerRealVPlus1 = BigInteger.valueOf(LOWER_REAL_V + 1); 310 | BigInteger lowerRealVReplayProtected = BigInteger.valueOf(REPLAY_PROTECTED_V_MIN); 311 | BigInteger chainIdInc = BigInteger.valueOf(CHAIN_ID_INC); 312 | if (v.equals(lowerRealV) || v.equals(lowerRealVPlus1)) { 313 | return v.subtract(lowerRealV).intValue(); 314 | } else if (v.compareTo(lowerRealVReplayProtected) >= 0) { 315 | return v.subtract(BigInteger.valueOf(chainId).multiply(TWO)) 316 | .subtract(chainIdInc) 317 | .intValue(); 318 | } else { 319 | throw new IllegalArgumentException(String.format("Unsupported v parameter: %s", v)); 320 | } 321 | } 322 | 323 | /** 324 | * Returns the header 'v'. 325 | * 326 | * @param recId The recovery id. 327 | * @return byte[] header 'v'. 328 | */ 329 | public static byte[] getVFromRecId(int recId) { 330 | return new byte[] {(byte) (LOWER_REAL_V + recId)}; 331 | } 332 | 333 | /** 334 | * Returns public key from the given private key. 335 | * 336 | * @param privKey the private key to derive the public key from 337 | * @return BigInteger encoded public key 338 | */ 339 | public static BigInteger publicKeyFromPrivate(BigInteger privKey) { 340 | ECPoint point = publicPointFromPrivate(privKey); 341 | 342 | byte[] encoded = point.getEncoded(false); 343 | return new BigInteger(1, Arrays.copyOfRange(encoded, 1, encoded.length)); // remove prefix 344 | } 345 | 346 | /** 347 | * Returns public key point from the given private key. 348 | * 349 | * @param privKey the private key to derive the public key from 350 | * @return ECPoint public key 351 | */ 352 | public static ECPoint publicPointFromPrivate(BigInteger privKey) { 353 | /* 354 | * TODO: FixedPointCombMultiplier currently doesn't support scalars longer than the group 355 | * order, but that could change in future versions. 356 | */ 357 | if (privKey.bitLength() > CURVE.getN().bitLength()) { 358 | privKey = privKey.mod(CURVE.getN()); 359 | } 360 | return new FixedPointCombMultiplier().multiply(CURVE.getG(), privKey); 361 | } 362 | 363 | /** 364 | * Returns public key point from the given curve. 365 | * 366 | * @param bits representing the point on the curve 367 | * @return BigInteger encoded public key 368 | */ 369 | public static BigInteger publicFromPoint(byte[] bits) { 370 | return new BigInteger(1, Arrays.copyOfRange(bits, 1, bits.length)); // remove prefix 371 | } 372 | 373 | public static class SignatureData { 374 | private final byte[] v; 375 | private final byte[] r; 376 | private final byte[] s; 377 | 378 | public SignatureData(byte v, byte[] r, byte[] s) { 379 | this(new byte[] {v}, r, s); 380 | } 381 | 382 | public SignatureData(byte[] v, byte[] r, byte[] s) { 383 | this.v = v; 384 | this.r = r; 385 | this.s = s; 386 | } 387 | 388 | public byte[] getV() { 389 | return v; 390 | } 391 | 392 | public byte[] getR() { 393 | return r; 394 | } 395 | 396 | public byte[] getS() { 397 | return s; 398 | } 399 | 400 | @Override 401 | public boolean equals(Object o) { 402 | if (this == o) { 403 | return true; 404 | } 405 | if (o == null || getClass() != o.getClass()) { 406 | return false; 407 | } 408 | 409 | SignatureData that = (SignatureData) o; 410 | 411 | if (!Arrays.equals(v, that.v)) { 412 | return false; 413 | } 414 | if (!Arrays.equals(r, that.r)) { 415 | return false; 416 | } 417 | return Arrays.equals(s, that.s); 418 | } 419 | 420 | @Override 421 | public int hashCode() { 422 | int result = Arrays.hashCode(v); 423 | result = 31 * result + Arrays.hashCode(r); 424 | result = 31 * result + Arrays.hashCode(s); 425 | return result; 426 | } 427 | } 428 | } 429 | -------------------------------------------------------------------------------- /src/main/java/pro/edgematrix/protocol/core/JsonRpc2_0Web3j.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Web3 Labs Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 5 | * the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on 10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the 11 | * specific language governing permissions and limitations under the License. 12 | */ 13 | package pro.edgematrix.protocol.core; 14 | 15 | import io.reactivex.Flowable; 16 | import org.web3j.protocol.Web3j; 17 | import org.web3j.protocol.Web3jService; 18 | import org.web3j.protocol.core.BatchRequest; 19 | import org.web3j.protocol.core.DefaultBlockParameter; 20 | import org.web3j.protocol.core.Request; 21 | import org.web3j.protocol.core.methods.request.ShhFilter; 22 | import org.web3j.protocol.core.methods.request.ShhPost; 23 | import org.web3j.protocol.core.methods.request.Transaction; 24 | import org.web3j.protocol.core.methods.response.*; 25 | import org.web3j.protocol.core.methods.response.admin.AdminDataDir; 26 | import org.web3j.protocol.core.methods.response.admin.AdminNodeInfo; 27 | import org.web3j.protocol.core.methods.response.admin.AdminPeers; 28 | import org.web3j.protocol.rx.JsonRpc2_0Rx; 29 | import org.web3j.protocol.websocket.events.LogNotification; 30 | import org.web3j.protocol.websocket.events.NewHeadsNotification; 31 | import org.web3j.utils.Async; 32 | import org.web3j.utils.Numeric; 33 | import pro.edgematrix.EdgeWeb3j; 34 | import pro.edgematrix.protocol.methods.response.EdgeSendRtcMsg; 35 | import pro.edgematrix.protocol.methods.response.EdgeSendTelegram; 36 | 37 | import java.io.IOException; 38 | import java.math.BigInteger; 39 | import java.util.*; 40 | import java.util.concurrent.ScheduledExecutorService; 41 | 42 | /** 43 | * JSON-RPC 2.0 factory implementation. 44 | */ 45 | public class JsonRpc2_0Web3j implements EdgeWeb3j, Web3j { 46 | 47 | public static final int DEFAULT_BLOCK_TIME = 15 * 1000; 48 | 49 | protected final Web3jService web3jService; 50 | private final JsonRpc2_0Rx web3jRx; 51 | private final long blockTime; 52 | private final ScheduledExecutorService scheduledExecutorService; 53 | 54 | public JsonRpc2_0Web3j(Web3jService web3jService) { 55 | this(web3jService, DEFAULT_BLOCK_TIME, Async.defaultExecutorService()); 56 | } 57 | 58 | public JsonRpc2_0Web3j( 59 | Web3jService web3jService, 60 | long pollingInterval, 61 | ScheduledExecutorService scheduledExecutorService) { 62 | this.web3jService = web3jService; 63 | this.web3jRx = new JsonRpc2_0Rx(this, scheduledExecutorService); 64 | this.blockTime = pollingInterval; 65 | this.scheduledExecutorService = scheduledExecutorService; 66 | } 67 | 68 | /** 69 | * edge json-rpc methods 70 | */ 71 | @Override 72 | public Request edgeGetTelegramReceipt(String telegramHash) { 73 | return new Request<>( 74 | "edge_getTelegramReceipt", 75 | Arrays.asList(telegramHash), 76 | web3jService, 77 | EthGetTransactionReceipt.class); 78 | } 79 | 80 | @Override 81 | public Request edgeGetTelegramCount( 82 | String address, DefaultBlockParameter defaultBlockParameter) { 83 | return new Request<>( 84 | "edge_getTelegramCount", 85 | Arrays.asList(address, defaultBlockParameter.getValue()), 86 | web3jService, 87 | EthGetTransactionCount.class); 88 | } 89 | 90 | @Override 91 | public Request 92 | edgeSendRawTelegram(String signedTransactionData) { 93 | return new Request<>( 94 | "edge_sendRawTelegram", 95 | Arrays.asList(signedTransactionData), 96 | web3jService, 97 | EdgeSendTelegram.class); 98 | } 99 | 100 | @Override 101 | public Request 102 | edgeSendRawMsg(String signedTransactionData) { 103 | return new Request<>( 104 | "edge_sendRawMsg", 105 | Arrays.asList(signedTransactionData), 106 | web3jService, 107 | EdgeSendRtcMsg.class); 108 | } 109 | 110 | /** 111 | * eth json-rpc methods 112 | */ 113 | 114 | @Override 115 | public Request web3ClientVersion() { 116 | return new Request<>( 117 | "web3_clientVersion", 118 | Collections.emptyList(), 119 | web3jService, 120 | Web3ClientVersion.class); 121 | } 122 | 123 | @Override 124 | public Request web3Sha3(String data) { 125 | return new Request<>("web3_sha3", Arrays.asList(data), web3jService, Web3Sha3.class); 126 | } 127 | 128 | @Override 129 | public Request netVersion() { 130 | return new Request<>( 131 | "net_version", Collections.emptyList(), web3jService, NetVersion.class); 132 | } 133 | 134 | @Override 135 | public Request netListening() { 136 | return new Request<>( 137 | "net_listening", Collections.emptyList(), web3jService, NetListening.class); 138 | } 139 | 140 | @Override 141 | public Request netPeerCount() { 142 | return new Request<>( 143 | "net_peerCount", Collections.emptyList(), web3jService, NetPeerCount.class); 144 | } 145 | 146 | @Override 147 | public Request adminNodeInfo() { 148 | return new Request<>( 149 | "admin_nodeInfo", Collections.emptyList(), web3jService, AdminNodeInfo.class); 150 | } 151 | 152 | @Override 153 | public Request adminPeers() { 154 | return new Request<>( 155 | "admin_peers", Collections.emptyList(), web3jService, AdminPeers.class); 156 | } 157 | 158 | @Override 159 | public Request adminAddPeer(String url) { 160 | return new Request<>( 161 | "admin_addPeer", Arrays.asList(url), web3jService, BooleanResponse.class); 162 | } 163 | 164 | @Override 165 | public Request adminRemovePeer(String url) { 166 | return new Request<>( 167 | "admin_removePeer", Arrays.asList(url), web3jService, BooleanResponse.class); 168 | } 169 | 170 | @Override 171 | public Request adminDataDir() { 172 | return new Request<>( 173 | "admin_datadir", Collections.emptyList(), web3jService, AdminDataDir.class); 174 | } 175 | 176 | @Override 177 | public Request ethProtocolVersion() { 178 | return new Request<>( 179 | "eth_protocolVersion", 180 | Collections.emptyList(), 181 | web3jService, 182 | EthProtocolVersion.class); 183 | } 184 | 185 | @Override 186 | public Request ethChainId() { 187 | return new Request<>( 188 | "eth_chainId", Collections.emptyList(), web3jService, EthChainId.class); 189 | } 190 | 191 | @Override 192 | public Request ethCoinbase() { 193 | return new Request<>( 194 | "eth_coinbase", Collections.emptyList(), web3jService, EthCoinbase.class); 195 | } 196 | 197 | @Override 198 | public Request ethSyncing() { 199 | return new Request<>( 200 | "eth_syncing", Collections.emptyList(), web3jService, EthSyncing.class); 201 | } 202 | 203 | @Override 204 | public Request ethMining() { 205 | return new Request<>( 206 | "eth_mining", Collections.emptyList(), web3jService, EthMining.class); 207 | } 208 | 209 | @Override 210 | public Request ethHashrate() { 211 | return new Request<>( 212 | "eth_hashrate", Collections.emptyList(), web3jService, EthHashrate.class); 213 | } 214 | 215 | @Override 216 | public Request ethGasPrice() { 217 | return new Request<>( 218 | "eth_gasPrice", Collections.emptyList(), web3jService, EthGasPrice.class); 219 | } 220 | 221 | @Override 222 | public Request ethMaxPriorityFeePerGas() { 223 | return new Request<>( 224 | "eth_maxPriorityFeePerGas", 225 | Collections.emptyList(), 226 | web3jService, 227 | EthMaxPriorityFeePerGas.class); 228 | } 229 | 230 | @Override 231 | public Request ethFeeHistory( 232 | int blockCount, DefaultBlockParameter newestBlock, List rewardPercentiles) { 233 | return new Request<>( 234 | "eth_feeHistory", 235 | Arrays.asList( 236 | Numeric.encodeQuantity(BigInteger.valueOf(blockCount)), 237 | newestBlock.getValue(), 238 | rewardPercentiles), 239 | web3jService, 240 | EthFeeHistory.class); 241 | } 242 | 243 | @Override 244 | public Request ethAccounts() { 245 | return new Request<>( 246 | "eth_accounts", Collections.emptyList(), web3jService, EthAccounts.class); 247 | } 248 | 249 | @Override 250 | public Request ethBlockNumber() { 251 | return new Request<>( 252 | "eth_blockNumber", 253 | Collections.emptyList(), 254 | web3jService, 255 | EthBlockNumber.class); 256 | } 257 | 258 | @Override 259 | public Request ethGetBalance( 260 | String address, DefaultBlockParameter defaultBlockParameter) { 261 | return new Request<>( 262 | "eth_getBalance", 263 | Arrays.asList(address, defaultBlockParameter.getValue()), 264 | web3jService, 265 | EthGetBalance.class); 266 | } 267 | 268 | @Override 269 | public Request ethGetStorageAt( 270 | String address, BigInteger position, DefaultBlockParameter defaultBlockParameter) { 271 | return new Request<>( 272 | "eth_getStorageAt", 273 | Arrays.asList( 274 | address, 275 | Numeric.encodeQuantity(position), 276 | defaultBlockParameter.getValue()), 277 | web3jService, 278 | EthGetStorageAt.class); 279 | } 280 | 281 | @Override 282 | public Request ethGetTransactionCount( 283 | String address, DefaultBlockParameter defaultBlockParameter) { 284 | return new Request<>( 285 | "eth_getTransactionCount", 286 | Arrays.asList(address, defaultBlockParameter.getValue()), 287 | web3jService, 288 | EthGetTransactionCount.class); 289 | } 290 | 291 | @Override 292 | public Request ethGetBlockTransactionCountByHash( 293 | String blockHash) { 294 | return new Request<>( 295 | "eth_getBlockTransactionCountByHash", 296 | Arrays.asList(blockHash), 297 | web3jService, 298 | EthGetBlockTransactionCountByHash.class); 299 | } 300 | 301 | @Override 302 | public Request ethGetBlockTransactionCountByNumber( 303 | DefaultBlockParameter defaultBlockParameter) { 304 | return new Request<>( 305 | "eth_getBlockTransactionCountByNumber", 306 | Arrays.asList(defaultBlockParameter.getValue()), 307 | web3jService, 308 | EthGetBlockTransactionCountByNumber.class); 309 | } 310 | 311 | @Override 312 | public Request ethGetUncleCountByBlockHash(String blockHash) { 313 | return new Request<>( 314 | "eth_getUncleCountByBlockHash", 315 | Arrays.asList(blockHash), 316 | web3jService, 317 | EthGetUncleCountByBlockHash.class); 318 | } 319 | 320 | @Override 321 | public Request ethGetUncleCountByBlockNumber( 322 | DefaultBlockParameter defaultBlockParameter) { 323 | return new Request<>( 324 | "eth_getUncleCountByBlockNumber", 325 | Arrays.asList(defaultBlockParameter.getValue()), 326 | web3jService, 327 | EthGetUncleCountByBlockNumber.class); 328 | } 329 | 330 | @Override 331 | public Request ethGetCode( 332 | String address, DefaultBlockParameter defaultBlockParameter) { 333 | return new Request<>( 334 | "eth_getCode", 335 | Arrays.asList(address, defaultBlockParameter.getValue()), 336 | web3jService, 337 | EthGetCode.class); 338 | } 339 | 340 | @Override 341 | public Request ethSign(String address, String sha3HashOfDataToSign) { 342 | return new Request<>( 343 | "eth_sign", 344 | Arrays.asList(address, sha3HashOfDataToSign), 345 | web3jService, 346 | EthSign.class); 347 | } 348 | 349 | @Override 350 | public Request 351 | ethSendTransaction(Transaction transaction) { 352 | return new Request<>( 353 | "eth_sendTransaction", 354 | Arrays.asList(transaction), 355 | web3jService, 356 | org.web3j.protocol.core.methods.response.EthSendTransaction.class); 357 | } 358 | 359 | @Override 360 | public Request 361 | ethSendRawTransaction(String signedTransactionData) { 362 | return new Request<>( 363 | "edge_sendRawTelegram", 364 | Arrays.asList(signedTransactionData), 365 | web3jService, 366 | org.web3j.protocol.core.methods.response.EthSendTransaction.class); 367 | } 368 | 369 | @Override 370 | public Request ethCall( 371 | Transaction transaction, DefaultBlockParameter defaultBlockParameter) { 372 | return new Request<>( 373 | "eth_call", 374 | Arrays.asList(transaction, defaultBlockParameter), 375 | web3jService, 376 | org.web3j.protocol.core.methods.response.EthCall.class); 377 | } 378 | 379 | @Override 380 | public Request ethEstimateGas(Transaction transaction) { 381 | return new Request<>( 382 | "eth_estimateGas", Arrays.asList(transaction), web3jService, EthEstimateGas.class); 383 | } 384 | 385 | @Override 386 | public Request ethGetBlockByHash( 387 | String blockHash, boolean returnFullTransactionObjects) { 388 | return new Request<>( 389 | "eth_getBlockByHash", 390 | Arrays.asList(blockHash, returnFullTransactionObjects), 391 | web3jService, 392 | EthBlock.class); 393 | } 394 | 395 | @Override 396 | public Request ethGetBlockByNumber( 397 | DefaultBlockParameter defaultBlockParameter, boolean returnFullTransactionObjects) { 398 | return new Request<>( 399 | "eth_getBlockByNumber", 400 | Arrays.asList(defaultBlockParameter.getValue(), returnFullTransactionObjects), 401 | web3jService, 402 | EthBlock.class); 403 | } 404 | 405 | @Override 406 | public Request ethGetTransactionByHash(String transactionHash) { 407 | return new Request<>( 408 | "eth_getTransactionByHash", 409 | Arrays.asList(transactionHash), 410 | web3jService, 411 | EthTransaction.class); 412 | } 413 | 414 | @Override 415 | public Request ethGetTransactionByBlockHashAndIndex( 416 | String blockHash, BigInteger transactionIndex) { 417 | return new Request<>( 418 | "eth_getTransactionByBlockHashAndIndex", 419 | Arrays.asList(blockHash, Numeric.encodeQuantity(transactionIndex)), 420 | web3jService, 421 | EthTransaction.class); 422 | } 423 | 424 | @Override 425 | public Request ethGetTransactionByBlockNumberAndIndex( 426 | DefaultBlockParameter defaultBlockParameter, BigInteger transactionIndex) { 427 | return new Request<>( 428 | "eth_getTransactionByBlockNumberAndIndex", 429 | Arrays.asList( 430 | defaultBlockParameter.getValue(), Numeric.encodeQuantity(transactionIndex)), 431 | web3jService, 432 | EthTransaction.class); 433 | } 434 | 435 | @Override 436 | public Request ethGetTransactionReceipt(String transactionHash) { 437 | return new Request<>( 438 | "eth_getTransactionReceipt", 439 | Arrays.asList(transactionHash), 440 | web3jService, 441 | EthGetTransactionReceipt.class); 442 | } 443 | 444 | @Override 445 | public Request ethGetBlockReceipts( 446 | DefaultBlockParameter defaultBlockParameter) { 447 | return new Request<>( 448 | "eth_getBlockReceipts", 449 | Arrays.asList(defaultBlockParameter.getValue()), 450 | web3jService, 451 | EthGetBlockReceipts.class); 452 | } 453 | 454 | @Override 455 | public Request ethGetUncleByBlockHashAndIndex( 456 | String blockHash, BigInteger transactionIndex) { 457 | return new Request<>( 458 | "eth_getUncleByBlockHashAndIndex", 459 | Arrays.asList(blockHash, Numeric.encodeQuantity(transactionIndex)), 460 | web3jService, 461 | EthBlock.class); 462 | } 463 | 464 | @Override 465 | public Request ethGetUncleByBlockNumberAndIndex( 466 | DefaultBlockParameter defaultBlockParameter, BigInteger uncleIndex) { 467 | return new Request<>( 468 | "eth_getUncleByBlockNumberAndIndex", 469 | Arrays.asList(defaultBlockParameter.getValue(), Numeric.encodeQuantity(uncleIndex)), 470 | web3jService, 471 | EthBlock.class); 472 | } 473 | 474 | @Override 475 | public Request ethGetCompilers() { 476 | return new Request<>( 477 | "eth_getCompilers", 478 | Collections.emptyList(), 479 | web3jService, 480 | EthGetCompilers.class); 481 | } 482 | 483 | @Override 484 | public Request ethCompileLLL(String sourceCode) { 485 | return new Request<>( 486 | "eth_compileLLL", Arrays.asList(sourceCode), web3jService, EthCompileLLL.class); 487 | } 488 | 489 | @Override 490 | public Request ethCompileSolidity(String sourceCode) { 491 | return new Request<>( 492 | "eth_compileSolidity", 493 | Arrays.asList(sourceCode), 494 | web3jService, 495 | EthCompileSolidity.class); 496 | } 497 | 498 | @Override 499 | public Request ethCompileSerpent(String sourceCode) { 500 | return new Request<>( 501 | "eth_compileSerpent", 502 | Arrays.asList(sourceCode), 503 | web3jService, 504 | EthCompileSerpent.class); 505 | } 506 | 507 | @Override 508 | public Request ethNewFilter( 509 | org.web3j.protocol.core.methods.request.EthFilter ethFilter) { 510 | return new Request<>( 511 | "eth_newFilter", Arrays.asList(ethFilter), web3jService, EthFilter.class); 512 | } 513 | 514 | @Override 515 | public Request ethNewBlockFilter() { 516 | return new Request<>( 517 | "eth_newBlockFilter", 518 | Collections.emptyList(), 519 | web3jService, 520 | EthFilter.class); 521 | } 522 | 523 | @Override 524 | public Request ethNewPendingTransactionFilter() { 525 | return new Request<>( 526 | "eth_newPendingTransactionFilter", 527 | Collections.emptyList(), 528 | web3jService, 529 | EthFilter.class); 530 | } 531 | 532 | @Override 533 | public Request ethUninstallFilter(BigInteger filterId) { 534 | return new Request<>( 535 | "eth_uninstallFilter", 536 | Arrays.asList(Numeric.toHexStringWithPrefix(filterId)), 537 | web3jService, 538 | EthUninstallFilter.class); 539 | } 540 | 541 | @Override 542 | public Request ethGetFilterChanges(BigInteger filterId) { 543 | return new Request<>( 544 | "eth_getFilterChanges", 545 | Arrays.asList(Numeric.toHexStringWithPrefix(filterId)), 546 | web3jService, 547 | EthLog.class); 548 | } 549 | 550 | @Override 551 | public Request ethGetFilterLogs(BigInteger filterId) { 552 | return new Request<>( 553 | "eth_getFilterLogs", 554 | Arrays.asList(Numeric.toHexStringWithPrefix(filterId)), 555 | web3jService, 556 | EthLog.class); 557 | } 558 | 559 | @Override 560 | public Request ethGetLogs( 561 | org.web3j.protocol.core.methods.request.EthFilter ethFilter) { 562 | return new Request<>("eth_getLogs", Arrays.asList(ethFilter), web3jService, EthLog.class); 563 | } 564 | 565 | @Override 566 | public Request ethGetWork() { 567 | return new Request<>( 568 | "eth_getWork", Collections.emptyList(), web3jService, EthGetWork.class); 569 | } 570 | 571 | @Override 572 | public Request ethSubmitWork( 573 | String nonce, String headerPowHash, String mixDigest) { 574 | return new Request<>( 575 | "eth_submitWork", 576 | Arrays.asList(nonce, headerPowHash, mixDigest), 577 | web3jService, 578 | EthSubmitWork.class); 579 | } 580 | 581 | @Override 582 | public Request ethSubmitHashrate(String hashrate, String clientId) { 583 | return new Request<>( 584 | "eth_submitHashrate", 585 | Arrays.asList(hashrate, clientId), 586 | web3jService, 587 | EthSubmitHashrate.class); 588 | } 589 | 590 | @Override 591 | public Request dbPutString( 592 | String databaseName, String keyName, String stringToStore) { 593 | return new Request<>( 594 | "db_putString", 595 | Arrays.asList(databaseName, keyName, stringToStore), 596 | web3jService, 597 | DbPutString.class); 598 | } 599 | 600 | @Override 601 | public Request dbGetString(String databaseName, String keyName) { 602 | return new Request<>( 603 | "db_getString", 604 | Arrays.asList(databaseName, keyName), 605 | web3jService, 606 | DbGetString.class); 607 | } 608 | 609 | @Override 610 | public Request dbPutHex(String databaseName, String keyName, String dataToStore) { 611 | return new Request<>( 612 | "db_putHex", 613 | Arrays.asList(databaseName, keyName, dataToStore), 614 | web3jService, 615 | DbPutHex.class); 616 | } 617 | 618 | @Override 619 | public Request dbGetHex(String databaseName, String keyName) { 620 | return new Request<>( 621 | "db_getHex", Arrays.asList(databaseName, keyName), web3jService, DbGetHex.class); 622 | } 623 | 624 | @Override 625 | public Request shhPost(ShhPost shhPost) { 626 | return new Request<>( 627 | "shh_post", 628 | Arrays.asList(shhPost), 629 | web3jService, 630 | org.web3j.protocol.core.methods.response.ShhPost.class); 631 | } 632 | 633 | @Override 634 | public Request shhVersion() { 635 | return new Request<>( 636 | "shh_version", Collections.emptyList(), web3jService, ShhVersion.class); 637 | } 638 | 639 | @Override 640 | public Request shhNewIdentity() { 641 | return new Request<>( 642 | "shh_newIdentity", 643 | Collections.emptyList(), 644 | web3jService, 645 | ShhNewIdentity.class); 646 | } 647 | 648 | @Override 649 | public Request shhHasIdentity(String identityAddress) { 650 | return new Request<>( 651 | "shh_hasIdentity", 652 | Arrays.asList(identityAddress), 653 | web3jService, 654 | ShhHasIdentity.class); 655 | } 656 | 657 | @Override 658 | public Request shhNewGroup() { 659 | return new Request<>( 660 | "shh_newGroup", Collections.emptyList(), web3jService, ShhNewGroup.class); 661 | } 662 | 663 | @Override 664 | public Request shhAddToGroup(String identityAddress) { 665 | return new Request<>( 666 | "shh_addToGroup", 667 | Arrays.asList(identityAddress), 668 | web3jService, 669 | ShhAddToGroup.class); 670 | } 671 | 672 | @Override 673 | public Request shhNewFilter(ShhFilter shhFilter) { 674 | return new Request<>( 675 | "shh_newFilter", Arrays.asList(shhFilter), web3jService, ShhNewFilter.class); 676 | } 677 | 678 | @Override 679 | public Request shhUninstallFilter(BigInteger filterId) { 680 | return new Request<>( 681 | "shh_uninstallFilter", 682 | Arrays.asList(Numeric.toHexStringWithPrefix(filterId)), 683 | web3jService, 684 | ShhUninstallFilter.class); 685 | } 686 | 687 | @Override 688 | public Request shhGetFilterChanges(BigInteger filterId) { 689 | return new Request<>( 690 | "shh_getFilterChanges", 691 | Arrays.asList(Numeric.toHexStringWithPrefix(filterId)), 692 | web3jService, 693 | ShhMessages.class); 694 | } 695 | 696 | @Override 697 | public Request shhGetMessages(BigInteger filterId) { 698 | return new Request<>( 699 | "shh_getMessages", 700 | Arrays.asList(Numeric.toHexStringWithPrefix(filterId)), 701 | web3jService, 702 | ShhMessages.class); 703 | } 704 | 705 | @Override 706 | public Request txPoolStatus() { 707 | return new Request<>( 708 | "txpool_status", Collections.emptyList(), web3jService, TxPoolStatus.class); 709 | } 710 | 711 | @Override 712 | public Flowable newHeadsNotifications() { 713 | return web3jService.subscribe( 714 | new Request<>( 715 | "eth_subscribe", 716 | Collections.singletonList("newHeads"), 717 | web3jService, 718 | EthSubscribe.class), 719 | "eth_unsubscribe", 720 | NewHeadsNotification.class); 721 | } 722 | 723 | @Override 724 | public Flowable logsNotifications( 725 | List addresses, List topics) { 726 | 727 | Map params = createLogsParams(addresses, topics); 728 | 729 | return web3jService.subscribe( 730 | new Request<>( 731 | "eth_subscribe", 732 | Arrays.asList("logs", params), 733 | web3jService, 734 | EthSubscribe.class), 735 | "eth_unsubscribe", 736 | LogNotification.class); 737 | } 738 | 739 | private Map createLogsParams(List addresses, List topics) { 740 | Map params = new HashMap<>(); 741 | if (!addresses.isEmpty()) { 742 | params.put("address", addresses); 743 | } 744 | if (!topics.isEmpty()) { 745 | params.put("topics", topics); 746 | } 747 | return params; 748 | } 749 | 750 | @Override 751 | public Flowable ethBlockHashFlowable() { 752 | return web3jRx.ethBlockHashFlowable(blockTime); 753 | } 754 | 755 | @Override 756 | public Flowable ethPendingTransactionHashFlowable() { 757 | return web3jRx.ethPendingTransactionHashFlowable(blockTime); 758 | } 759 | 760 | @Override 761 | public Flowable ethLogFlowable( 762 | org.web3j.protocol.core.methods.request.EthFilter ethFilter) { 763 | return web3jRx.ethLogFlowable(ethFilter, blockTime); 764 | } 765 | 766 | @Override 767 | public Flowable transactionFlowable() { 768 | return web3jRx.transactionFlowable(blockTime); 769 | } 770 | 771 | @Override 772 | public Flowable 773 | pendingTransactionFlowable() { 774 | return web3jRx.pendingTransactionFlowable(blockTime); 775 | } 776 | 777 | @Override 778 | public Flowable blockFlowable(boolean fullTransactionObjects) { 779 | return web3jRx.blockFlowable(fullTransactionObjects, blockTime); 780 | } 781 | 782 | @Override 783 | public Flowable replayPastBlocksFlowable( 784 | DefaultBlockParameter startBlock, 785 | DefaultBlockParameter endBlock, 786 | boolean fullTransactionObjects) { 787 | return web3jRx.replayBlocksFlowable(startBlock, endBlock, fullTransactionObjects); 788 | } 789 | 790 | @Override 791 | public Flowable replayPastBlocksFlowable( 792 | DefaultBlockParameter startBlock, 793 | DefaultBlockParameter endBlock, 794 | boolean fullTransactionObjects, 795 | boolean ascending) { 796 | return web3jRx.replayBlocksFlowable( 797 | startBlock, endBlock, fullTransactionObjects, ascending); 798 | } 799 | 800 | @Override 801 | public Flowable replayPastBlocksFlowable( 802 | DefaultBlockParameter startBlock, 803 | boolean fullTransactionObjects, 804 | Flowable onCompleteFlowable) { 805 | return web3jRx.replayPastBlocksFlowable( 806 | startBlock, fullTransactionObjects, onCompleteFlowable); 807 | } 808 | 809 | @Override 810 | public Flowable replayPastBlocksFlowable( 811 | DefaultBlockParameter startBlock, boolean fullTransactionObjects) { 812 | return web3jRx.replayPastBlocksFlowable(startBlock, fullTransactionObjects); 813 | } 814 | 815 | @Override 816 | public Flowable 817 | replayPastTransactionsFlowable( 818 | DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { 819 | return web3jRx.replayTransactionsFlowable(startBlock, endBlock); 820 | } 821 | 822 | @Override 823 | public Flowable 824 | replayPastTransactionsFlowable(DefaultBlockParameter startBlock) { 825 | return web3jRx.replayPastTransactionsFlowable(startBlock); 826 | } 827 | 828 | @Override 829 | public Flowable replayPastAndFutureBlocksFlowable( 830 | DefaultBlockParameter startBlock, boolean fullTransactionObjects) { 831 | return web3jRx.replayPastAndFutureBlocksFlowable( 832 | startBlock, fullTransactionObjects, blockTime); 833 | } 834 | 835 | @Override 836 | public Flowable 837 | replayPastAndFutureTransactionsFlowable(DefaultBlockParameter startBlock) { 838 | return web3jRx.replayPastAndFutureTransactionsFlowable(startBlock, blockTime); 839 | } 840 | 841 | @Override 842 | public void shutdown() { 843 | scheduledExecutorService.shutdown(); 844 | try { 845 | web3jService.close(); 846 | } catch (IOException e) { 847 | throw new RuntimeException("Failed to close web3j service", e); 848 | } 849 | } 850 | 851 | @Override 852 | public BatchRequest newBatch() { 853 | return new BatchRequest(web3jService); 854 | } 855 | } 856 | --------------------------------------------------------------------------------