diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index eee6a1848..000000000 --- a/Dockerfile +++ /dev/null @@ -1,20 +0,0 @@ -FROM gradle:8.7.0-jdk-21-and-22-graal-jammy AS build_image - -WORKDIR /usr/build/ - -COPY . . -RUN gradle clean build -x test - -FROM sapmachine:21 - -RUN apt-get update && \ - apt-get install -y libstdc++6 && \ - apt-get clean && \ - rm -rf /var/lib/apt/lists/* - -WORKDIR /usr/app/ - -COPY src/main/webapp/genesis /usr/app/genesis -COPY --from=build_image /usr/build/build/libs/*.jar /usr/app/app.jar - -ENTRYPOINT ["java","-jar","/usr/app/app.jar"] \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts index 7aa64120d..547195018 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,8 +1,8 @@ plugins { id("java") id("war") - id("org.teavm") version "0.9.2" - id("io.freefair.lombok") version "8.6" + id("org.teavm") version "0.10.0" + id("io.freefair.lombok") version "8.7.1" } group = "com.limechain" @@ -20,31 +20,21 @@ dependencies { compileOnly("org.projectlombok:lombok:1.18.34") implementation("org.projectlombok:lombok:1.18.34") - implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar")))) - - implementation("org.javatuples:javatuples:1.2") - -// implementation("com.github.LimeChain:nabu:0.7.8") -// implementation("com.fasterxml.jackson.core:jackson-databind:2.17.2") - - implementation("org.teavm:teavm-jso-apis:0.9.2") + implementation("org.teavm:teavm-jso-apis:0.10.0") } -tasks.getByName("test") { - useJUnitPlatform() - jvmArgs("-Dnet.bytebuddy.experimental=true") -} - teavm.js { addedToWebApp = true mainClass = "com.limechain.Main" targetFileName = "fruzhin.js" } -//teavm { -// js { -// sourceMap.set(true) -// debugInformation.set(true) -// } -//} \ No newline at end of file + +//TODO: Debug only. Remove when doing release build +teavm { + js { + sourceMap.set(true) + debugInformation.set(true) + } +} \ No newline at end of file diff --git a/libs/polkaj-common-types-0.5.0-SNAPSHOT.jar b/libs/polkaj-common-types-0.5.0-SNAPSHOT.jar deleted file mode 100644 index ca3701acc..000000000 Binary files a/libs/polkaj-common-types-0.5.0-SNAPSHOT.jar and /dev/null differ diff --git a/libs/polkaj-scale-0.5.0-SNAPSHOT.jar b/libs/polkaj-scale-0.5.0-SNAPSHOT.jar deleted file mode 100644 index 99dd3ef98..000000000 Binary files a/libs/polkaj-scale-0.5.0-SNAPSHOT.jar and /dev/null differ diff --git a/libs/polkaj-scale-types-0.5.0-SNAPSHOT.jar b/libs/polkaj-scale-types-0.5.0-SNAPSHOT.jar deleted file mode 100644 index 158779f1c..000000000 Binary files a/libs/polkaj-scale-types-0.5.0-SNAPSHOT.jar and /dev/null differ diff --git a/local_dev.sh b/local_dev.sh deleted file mode 100755 index 37747e7f1..000000000 --- a/local_dev.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/bash - -# Fetch chain spec -chain_spec_resp=$(curl -H "Content-Type: application/json" -d '{"id":1, "jsonrpc":"2.0", "method": "sync_state_genSyncSpec", "params": [true]}' http://localhost:9944) -# Fetch boot nodes -boot_nodes_resp=$(curl -H "Content-Type: application/json" -d '{"id":1, "jsonrpc":"2.0", "method": "system_localListenAddresses"}' http://localhost:9944) - -# Remove "raw" to comply with Fruzhin project spec -output_json=$(echo "$chain_spec_resp" | jq '.result | .genesis |= . + .raw | del(.genesis.raw)') -# Extract boot nodes result from RPC json -boot_nodes=$(echo "$boot_nodes_resp" | jq '.result') -# Paste boot nodes -final_json=$(echo "$output_json" | jq --argjson bootNodes "$boot_nodes" '.bootNodes = $bootNodes') - -echo "$final_json" > "./src/main/webapp/genesis/westend-local.json" \ No newline at end of file diff --git a/src/main/java/com/limechain/Main.java b/src/main/java/com/limechain/Main.java index c8bea96e7..585a87d24 100644 --- a/src/main/java/com/limechain/Main.java +++ b/src/main/java/com/limechain/Main.java @@ -1,11 +1,14 @@ package com.limechain; import com.limechain.client.HostNode; +import com.limechain.client.LightClient; import com.limechain.config.HostConfig; import com.limechain.rpc.server.AppBean; import com.limechain.rpc.server.RpcApp; import com.limechain.utils.DivLogger; +import java.util.logging.Level; + public class Main { private static final DivLogger log = new DivLogger(); @@ -15,28 +18,11 @@ public static void main(String[] args) { RpcApp rpcApp = new RpcApp(); rpcApp.start(); - HostConfig hostConfig = AppBean.getBean(HostConfig.class); - - // Figure out what client role we want to start -// final NodeRole nodeRole = hostConfig.getNodeRole(); - HostNode client; - -// switch (nodeRole) { -// case LIGHT -> client = new LightClient(); -// case NONE -> { -// // This shouldn't happen. -// return; -// } -// default -> { -// log.log(Level.SEVERE, "Node role {0} not yet implemented.", nodeRole); -// return; -// } -// } + HostNode client = new LightClient(); // Start the client // NOTE: This starts the beans the client would need - mutates the global context -// client.start(); -// log.log(Level.INFO, "\uD83D\uDE80Started {0} client!", nodeRole); - + client.start(); + log.log(Level.INFO, "\uD83D\uDE80Started light client!"); } } \ No newline at end of file diff --git a/src/main/java/com/limechain/chain/lightsyncstate/AuthoritySet.java b/src/main/java/com/limechain/chain/lightsyncstate/AuthoritySet.java index 32ec4556a..dd9e9a929 100644 --- a/src/main/java/com/limechain/chain/lightsyncstate/AuthoritySet.java +++ b/src/main/java/com/limechain/chain/lightsyncstate/AuthoritySet.java @@ -1,9 +1,9 @@ package com.limechain.chain.lightsyncstate; -import io.emeraldpay.polkaj.types.Hash256; +import com.limechain.polkaj.Hash256; import lombok.Getter; import lombok.Setter; -import org.javatuples.Pair; +import com.limechain.tuple.Pair; import java.math.BigInteger; diff --git a/src/main/java/com/limechain/chain/lightsyncstate/BabeEpoch.java b/src/main/java/com/limechain/chain/lightsyncstate/BabeEpoch.java index 2e978df51..6205f05b6 100644 --- a/src/main/java/com/limechain/chain/lightsyncstate/BabeEpoch.java +++ b/src/main/java/com/limechain/chain/lightsyncstate/BabeEpoch.java @@ -2,7 +2,7 @@ import lombok.Getter; import lombok.Setter; -import org.javatuples.Pair; +import com.limechain.tuple.Pair; import java.math.BigInteger; import java.util.List; diff --git a/src/main/java/com/limechain/chain/lightsyncstate/EpochChanges.java b/src/main/java/com/limechain/chain/lightsyncstate/EpochChanges.java index 983c04726..86ed948e4 100644 --- a/src/main/java/com/limechain/chain/lightsyncstate/EpochChanges.java +++ b/src/main/java/com/limechain/chain/lightsyncstate/EpochChanges.java @@ -1,9 +1,9 @@ package com.limechain.chain.lightsyncstate; -import io.emeraldpay.polkaj.types.Hash256; +import com.limechain.polkaj.Hash256; import lombok.Getter; import lombok.Setter; -import org.javatuples.Pair; +import com.limechain.tuple.Pair; import java.math.BigInteger; import java.util.Map; diff --git a/src/main/java/com/limechain/chain/lightsyncstate/ForkTree.java b/src/main/java/com/limechain/chain/lightsyncstate/ForkTree.java index 7ce87fb19..559abfb92 100644 --- a/src/main/java/com/limechain/chain/lightsyncstate/ForkTree.java +++ b/src/main/java/com/limechain/chain/lightsyncstate/ForkTree.java @@ -1,6 +1,6 @@ package com.limechain.chain.lightsyncstate; -import io.emeraldpay.polkaj.types.Hash256; +import com.limechain.polkaj.Hash256; import lombok.Getter; import lombok.Setter; diff --git a/src/main/java/com/limechain/chain/lightsyncstate/LightSyncState.java b/src/main/java/com/limechain/chain/lightsyncstate/LightSyncState.java index 6913d0822..4d39b6df4 100644 --- a/src/main/java/com/limechain/chain/lightsyncstate/LightSyncState.java +++ b/src/main/java/com/limechain/chain/lightsyncstate/LightSyncState.java @@ -2,15 +2,19 @@ import com.limechain.chain.lightsyncstate.scale.AuthoritySetReader; import com.limechain.chain.lightsyncstate.scale.EpochChangesReader; +import com.limechain.network.protocol.warp.dto.BlockHeader; +import com.limechain.network.protocol.warp.scale.reader.BlockHeaderReader; +import com.limechain.polkaj.reader.ScaleCodecReader; import com.limechain.utils.StringUtils; -import io.emeraldpay.polkaj.scale.ScaleCodecReader; import lombok.Getter; +import lombok.ToString; +import java.util.Arrays; import java.util.Map; @Getter public class LightSyncState { -// private BlockHeader finalizedBlockHeader; + private BlockHeader finalizedBlockHeader; private EpochChanges epochChanges; private AuthoritySet grandpaAuthoritySet; @@ -29,12 +33,15 @@ public static LightSyncState decode(Map lightSyncState) { throw new IllegalStateException("grandpaAuthoritySet is null"); } + var state = new LightSyncState(); -// state.finalizedBlockHeader = new BlockHeaderReader() -// .read(new ScaleCodecReader(StringUtils.hexToBytes(header))); + byte[] bytes = StringUtils.hexToBytes(header); + state.finalizedBlockHeader = new BlockHeaderReader() + .read(new ScaleCodecReader(bytes)); + byte[] bytes1 = StringUtils.hexToBytes(epochChanges); state.epochChanges = new EpochChangesReader() - .read(new ScaleCodecReader(StringUtils.hexToBytes(epochChanges))); + .read(new ScaleCodecReader(bytes1)); state.grandpaAuthoritySet = new AuthoritySetReader() .read(new ScaleCodecReader(StringUtils.hexToBytes(grandpaAuthoritySet))); diff --git a/src/main/java/com/limechain/chain/lightsyncstate/PendingChange.java b/src/main/java/com/limechain/chain/lightsyncstate/PendingChange.java index 83407ee6b..2ff593604 100644 --- a/src/main/java/com/limechain/chain/lightsyncstate/PendingChange.java +++ b/src/main/java/com/limechain/chain/lightsyncstate/PendingChange.java @@ -1,6 +1,6 @@ package com.limechain.chain.lightsyncstate; -import io.emeraldpay.polkaj.types.Hash256; +import com.limechain.polkaj.Hash256; import lombok.Getter; import lombok.Setter; diff --git a/src/main/java/com/limechain/chain/lightsyncstate/scale/AuthorityReader.java b/src/main/java/com/limechain/chain/lightsyncstate/scale/AuthorityReader.java index 16b9d96f1..afc1ca8d0 100644 --- a/src/main/java/com/limechain/chain/lightsyncstate/scale/AuthorityReader.java +++ b/src/main/java/com/limechain/chain/lightsyncstate/scale/AuthorityReader.java @@ -1,9 +1,9 @@ package com.limechain.chain.lightsyncstate.scale; import com.limechain.chain.lightsyncstate.Authority; -import io.emeraldpay.polkaj.scale.ScaleCodecReader; -import io.emeraldpay.polkaj.scale.ScaleReader; -import io.emeraldpay.polkaj.scale.reader.UInt64Reader; +import com.limechain.polkaj.reader.ScaleCodecReader; +import com.limechain.polkaj.reader.ScaleReader; +import com.limechain.polkaj.reader.UInt64Reader; public class AuthorityReader implements ScaleReader { @Override diff --git a/src/main/java/com/limechain/chain/lightsyncstate/scale/AuthoritySetChangeReader.java b/src/main/java/com/limechain/chain/lightsyncstate/scale/AuthoritySetChangeReader.java index 81f622559..9e5242ba2 100644 --- a/src/main/java/com/limechain/chain/lightsyncstate/scale/AuthoritySetChangeReader.java +++ b/src/main/java/com/limechain/chain/lightsyncstate/scale/AuthoritySetChangeReader.java @@ -1,9 +1,9 @@ package com.limechain.chain.lightsyncstate.scale; -import io.emeraldpay.polkaj.scale.ScaleCodecReader; -import io.emeraldpay.polkaj.scale.ScaleReader; -import io.emeraldpay.polkaj.scale.reader.UInt64Reader; -import org.javatuples.Pair; +import com.limechain.polkaj.reader.ScaleCodecReader; +import com.limechain.polkaj.reader.ScaleReader; +import com.limechain.polkaj.reader.UInt64Reader; +import com.limechain.tuple.Pair; import java.math.BigInteger; diff --git a/src/main/java/com/limechain/chain/lightsyncstate/scale/AuthoritySetReader.java b/src/main/java/com/limechain/chain/lightsyncstate/scale/AuthoritySetReader.java index 317fa4714..d8f40f5f1 100644 --- a/src/main/java/com/limechain/chain/lightsyncstate/scale/AuthoritySetReader.java +++ b/src/main/java/com/limechain/chain/lightsyncstate/scale/AuthoritySetReader.java @@ -4,12 +4,12 @@ import com.limechain.chain.lightsyncstate.AuthoritySet; import com.limechain.chain.lightsyncstate.ForkTree; import com.limechain.chain.lightsyncstate.PendingChange; -import io.emeraldpay.polkaj.scale.ScaleCodecReader; -import io.emeraldpay.polkaj.scale.ScaleReader; -import io.emeraldpay.polkaj.scale.reader.ListReader; -import io.emeraldpay.polkaj.scale.reader.UInt32Reader; -import io.emeraldpay.polkaj.scale.reader.UInt64Reader; -import org.javatuples.Pair; +import com.limechain.polkaj.reader.ListReader; +import com.limechain.polkaj.reader.ScaleCodecReader; +import com.limechain.polkaj.reader.ScaleReader; +import com.limechain.polkaj.reader.UInt32Reader; +import com.limechain.polkaj.reader.UInt64Reader; +import com.limechain.tuple.Pair; public class AuthoritySetReader implements ScaleReader { @Override diff --git a/src/main/java/com/limechain/chain/lightsyncstate/scale/BabeConfigReader.java b/src/main/java/com/limechain/chain/lightsyncstate/scale/BabeConfigReader.java index 39c9fb78d..5fd6b8af8 100644 --- a/src/main/java/com/limechain/chain/lightsyncstate/scale/BabeConfigReader.java +++ b/src/main/java/com/limechain/chain/lightsyncstate/scale/BabeConfigReader.java @@ -1,10 +1,10 @@ package com.limechain.chain.lightsyncstate.scale; import com.limechain.chain.lightsyncstate.BabeEpoch; -import io.emeraldpay.polkaj.scale.ScaleCodecReader; -import io.emeraldpay.polkaj.scale.ScaleReader; -import io.emeraldpay.polkaj.scale.reader.UInt64Reader; -import org.javatuples.Pair; +import com.limechain.polkaj.reader.ScaleCodecReader; +import com.limechain.polkaj.reader.ScaleReader; +import com.limechain.polkaj.reader.UInt64Reader; +import com.limechain.tuple.Pair; public class BabeConfigReader implements ScaleReader { @Override diff --git a/src/main/java/com/limechain/chain/lightsyncstate/scale/BabeEpochReader.java b/src/main/java/com/limechain/chain/lightsyncstate/scale/BabeEpochReader.java index e29156e9d..4b9e15b06 100644 --- a/src/main/java/com/limechain/chain/lightsyncstate/scale/BabeEpochReader.java +++ b/src/main/java/com/limechain/chain/lightsyncstate/scale/BabeEpochReader.java @@ -1,10 +1,10 @@ package com.limechain.chain.lightsyncstate.scale; import com.limechain.chain.lightsyncstate.BabeEpoch; -import io.emeraldpay.polkaj.scale.ScaleCodecReader; -import io.emeraldpay.polkaj.scale.ScaleReader; -import io.emeraldpay.polkaj.scale.reader.ListReader; -import io.emeraldpay.polkaj.scale.reader.UInt64Reader; +import com.limechain.polkaj.reader.ListReader; +import com.limechain.polkaj.reader.ScaleCodecReader; +import com.limechain.polkaj.reader.ScaleReader; +import com.limechain.polkaj.reader.UInt64Reader; public class BabeEpochReader implements ScaleReader { @Override diff --git a/src/main/java/com/limechain/chain/lightsyncstate/scale/DelayKindReader.java b/src/main/java/com/limechain/chain/lightsyncstate/scale/DelayKindReader.java index 28367d12d..bc3e636ff 100644 --- a/src/main/java/com/limechain/chain/lightsyncstate/scale/DelayKindReader.java +++ b/src/main/java/com/limechain/chain/lightsyncstate/scale/DelayKindReader.java @@ -1,9 +1,9 @@ package com.limechain.chain.lightsyncstate.scale; import com.limechain.chain.lightsyncstate.PendingChange; -import io.emeraldpay.polkaj.scale.ScaleCodecReader; -import io.emeraldpay.polkaj.scale.ScaleReader; -import io.emeraldpay.polkaj.scale.reader.UInt32Reader; +import com.limechain.polkaj.reader.ScaleCodecReader; +import com.limechain.polkaj.reader.ScaleReader; +import com.limechain.polkaj.reader.UInt32Reader; import java.math.BigInteger; diff --git a/src/main/java/com/limechain/chain/lightsyncstate/scale/EpochChangesReader.java b/src/main/java/com/limechain/chain/lightsyncstate/scale/EpochChangesReader.java index be9abf2b4..00318fd8b 100644 --- a/src/main/java/com/limechain/chain/lightsyncstate/scale/EpochChangesReader.java +++ b/src/main/java/com/limechain/chain/lightsyncstate/scale/EpochChangesReader.java @@ -3,16 +3,18 @@ import com.limechain.chain.lightsyncstate.EpochChanges; import com.limechain.chain.lightsyncstate.ForkTree; import com.limechain.chain.lightsyncstate.PersistedEpoch; -import io.emeraldpay.polkaj.scale.ScaleCodecReader; -import io.emeraldpay.polkaj.scale.ScaleReader; -import io.emeraldpay.polkaj.scale.reader.ListReader; -import io.emeraldpay.polkaj.scale.reader.UInt32Reader; -import io.emeraldpay.polkaj.types.Hash256; -import org.javatuples.Pair; +import com.limechain.chain.lightsyncstate.PersistedEpochHeader; +import com.limechain.polkaj.Hash256; +import com.limechain.polkaj.reader.ListReader; +import com.limechain.polkaj.reader.ScaleCodecReader; +import com.limechain.polkaj.reader.ScaleReader; +import com.limechain.polkaj.reader.UInt32Reader; +import com.limechain.tuple.Pair; import java.math.BigInteger; +import java.util.HashMap; +import java.util.List; import java.util.Map; -import java.util.TreeMap; public class EpochChangesReader implements ScaleReader { @Override @@ -20,21 +22,22 @@ public EpochChanges read(ScaleCodecReader reader) { EpochChanges changes = new EpochChanges(); var forkTree = new ForkTree<>(); - forkTree.setRoots(reader.read(new ListReader<>( - new ForkTreeNodeReader<>( - new PersistedEpochHeaderReader() - ))) - .toArray(ForkTree.ForkTreeNode[]::new)); + PersistedEpochHeaderReader epochHeaderReader = new PersistedEpochHeaderReader(); + ForkTreeNodeReader forkTreeReader = new ForkTreeNodeReader<>(epochHeaderReader); + ListReader> listReader = new ListReader<>(forkTreeReader); + List> roots = reader.read(listReader); + forkTree.setRoots(roots.toArray(ForkTree.ForkTreeNode[]::new)); forkTree.setBestFinalizedNumber(reader.readOptional(new UInt32Reader())); - Map, PersistedEpoch> epochs = new TreeMap<>(); + PersistedEpochReader scaleReader = new PersistedEpochReader(); + + Map, PersistedEpoch> epochs = new HashMap<>(); int epochsCount = reader.readCompactInt(); for (int i = 0; i < epochsCount; i++) { - Pair key = new Pair<>( - new Hash256(reader.readUint256()), - BigInteger.valueOf(reader.readUint32()) - ); - var value = reader.read(new PersistedEpochReader()); + Hash256 hash256 = new Hash256(reader.readUint256()); + BigInteger bigInteger = BigInteger.valueOf(reader.readUint32()); + Pair key = new Pair<>(hash256, bigInteger); + var value = reader.read(scaleReader); epochs.put(key, value); } diff --git a/src/main/java/com/limechain/chain/lightsyncstate/scale/EpochHeaderReader.java b/src/main/java/com/limechain/chain/lightsyncstate/scale/EpochHeaderReader.java index 17edc950e..9fc6cc504 100644 --- a/src/main/java/com/limechain/chain/lightsyncstate/scale/EpochHeaderReader.java +++ b/src/main/java/com/limechain/chain/lightsyncstate/scale/EpochHeaderReader.java @@ -1,9 +1,9 @@ package com.limechain.chain.lightsyncstate.scale; import com.limechain.chain.lightsyncstate.EpochHeader; -import io.emeraldpay.polkaj.scale.ScaleCodecReader; -import io.emeraldpay.polkaj.scale.ScaleReader; -import io.emeraldpay.polkaj.scale.reader.UInt64Reader; +import com.limechain.polkaj.reader.ScaleCodecReader; +import com.limechain.polkaj.reader.ScaleReader; +import com.limechain.polkaj.reader.UInt64Reader; public class EpochHeaderReader implements ScaleReader { @Override diff --git a/src/main/java/com/limechain/chain/lightsyncstate/scale/ForkTreeNodeReader.java b/src/main/java/com/limechain/chain/lightsyncstate/scale/ForkTreeNodeReader.java index 65dc2fbcd..7e2c3e5ba 100644 --- a/src/main/java/com/limechain/chain/lightsyncstate/scale/ForkTreeNodeReader.java +++ b/src/main/java/com/limechain/chain/lightsyncstate/scale/ForkTreeNodeReader.java @@ -1,10 +1,10 @@ package com.limechain.chain.lightsyncstate.scale; import com.limechain.chain.lightsyncstate.ForkTree; -import io.emeraldpay.polkaj.scale.ScaleCodecReader; -import io.emeraldpay.polkaj.scale.ScaleReader; -import io.emeraldpay.polkaj.scale.reader.ListReader; -import io.emeraldpay.polkaj.types.Hash256; +import com.limechain.polkaj.Hash256; +import com.limechain.polkaj.reader.ListReader; +import com.limechain.polkaj.reader.ScaleCodecReader; +import com.limechain.polkaj.reader.ScaleReader; import java.math.BigInteger; diff --git a/src/main/java/com/limechain/chain/lightsyncstate/scale/PendingChangeReader.java b/src/main/java/com/limechain/chain/lightsyncstate/scale/PendingChangeReader.java index 566e18b7a..d5b8ab2a7 100644 --- a/src/main/java/com/limechain/chain/lightsyncstate/scale/PendingChangeReader.java +++ b/src/main/java/com/limechain/chain/lightsyncstate/scale/PendingChangeReader.java @@ -1,10 +1,10 @@ package com.limechain.chain.lightsyncstate.scale; import com.limechain.chain.lightsyncstate.PendingChange; -import io.emeraldpay.polkaj.scale.ScaleCodecReader; -import io.emeraldpay.polkaj.scale.ScaleReader; -import io.emeraldpay.polkaj.scale.reader.ListReader; -import io.emeraldpay.polkaj.types.Hash256; +import com.limechain.polkaj.Hash256; +import com.limechain.polkaj.reader.ListReader; +import com.limechain.polkaj.reader.ScaleCodecReader; +import com.limechain.polkaj.reader.ScaleReader; import java.math.BigInteger; diff --git a/src/main/java/com/limechain/chain/lightsyncstate/scale/PersistedEpochHeaderReader.java b/src/main/java/com/limechain/chain/lightsyncstate/scale/PersistedEpochHeaderReader.java index 4815ef391..b6c943b32 100644 --- a/src/main/java/com/limechain/chain/lightsyncstate/scale/PersistedEpochHeaderReader.java +++ b/src/main/java/com/limechain/chain/lightsyncstate/scale/PersistedEpochHeaderReader.java @@ -2,8 +2,8 @@ import com.limechain.chain.lightsyncstate.EpochHeader; import com.limechain.chain.lightsyncstate.PersistedEpochHeader; -import io.emeraldpay.polkaj.scale.ScaleCodecReader; -import io.emeraldpay.polkaj.scale.ScaleReader; +import com.limechain.polkaj.reader.ScaleCodecReader; +import com.limechain.polkaj.reader.ScaleReader; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/com/limechain/chain/lightsyncstate/scale/PersistedEpochReader.java b/src/main/java/com/limechain/chain/lightsyncstate/scale/PersistedEpochReader.java index 6d4c2923c..4a3f31222 100644 --- a/src/main/java/com/limechain/chain/lightsyncstate/scale/PersistedEpochReader.java +++ b/src/main/java/com/limechain/chain/lightsyncstate/scale/PersistedEpochReader.java @@ -2,8 +2,8 @@ import com.limechain.chain.lightsyncstate.BabeEpoch; import com.limechain.chain.lightsyncstate.PersistedEpoch; -import io.emeraldpay.polkaj.scale.ScaleCodecReader; -import io.emeraldpay.polkaj.scale.ScaleReader; +import com.limechain.polkaj.reader.ScaleCodecReader; +import com.limechain.polkaj.reader.ScaleReader; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/com/limechain/client/LightClient.java b/src/main/java/com/limechain/client/LightClient.java index 2084642b2..0e5bcc969 100644 --- a/src/main/java/com/limechain/client/LightClient.java +++ b/src/main/java/com/limechain/client/LightClient.java @@ -35,16 +35,14 @@ public void start() { this.network.start(); while (true) { -// if (network.getKademliaService().getBootNodePeerIds().size() > 0) { -// if (this.network.getKademliaService().getSuccessfulBootNodes() > 0) { -// log.log(Level.INFO, "Node successfully connected to a peer! Sync can start!"); -// this.warpSyncMachine = AppBean.getBean(WarpSyncMachine.class); -// this.warpSyncMachine.start(); -// break; -// } else { -// this.network.updateCurrentSelectedPeer(); -// } -// } + if (this.network.getKademliaService().getSuccessfulBootNodes() > 0) { + log.log(Level.INFO, "Node successfully connected to a peer! Sync can start!"); + this.warpSyncMachine = AppBean.getBean(WarpSyncMachine.class); + this.warpSyncMachine.start(); + break; + } else { + this.network.updateCurrentSelectedPeer(); + } log.log(Level.INFO, "Waiting for peer connection..."); Thread.sleep(10000); } diff --git a/src/main/java/com/limechain/config/SystemInfo.java b/src/main/java/com/limechain/config/SystemInfo.java index 5d159d562..b2fafd50b 100644 --- a/src/main/java/com/limechain/config/SystemInfo.java +++ b/src/main/java/com/limechain/config/SystemInfo.java @@ -6,6 +6,7 @@ import lombok.Getter; import java.math.BigInteger; +import java.util.Map; import java.util.logging.Level; /** @@ -23,14 +24,10 @@ public class SystemInfo { private static final DivLogger log = new DivLogger(); public SystemInfo(HostConfig hostConfig, SyncState syncState) { - log.log("Building SystemInfo constructor"); // this.role = network.getNodeRole().name(); this.chain = hostConfig.getChain(); - log.log("getChain"); // this.hostIdentity = network.getHost().getPeerId().toString(); this.highestBlock = syncState.getLastFinalizedBlockNumber(); - - log.log("SystemInfo built"); logSystemInfo(); } @@ -51,7 +48,6 @@ public void logSystemInfo() { // log.log(Level.INFO, authEmoji + "Role: " + role); // log.log(Level.INFO, "Local node identity is: " + hostIdentity); log.log(Level.INFO, "Operating System: " + System.getProperty("os.name")); - log.log(Level.INFO, "CPU architecture: " + System.getProperty("os.arch")); log.log(Level.INFO, "Highest known block at #" + highestBlock); } } diff --git a/src/main/java/com/limechain/constants/GenesisBlockHash.java b/src/main/java/com/limechain/constants/GenesisBlockHash.java index c9a478896..2ffbec72c 100644 --- a/src/main/java/com/limechain/constants/GenesisBlockHash.java +++ b/src/main/java/com/limechain/constants/GenesisBlockHash.java @@ -1,6 +1,6 @@ package com.limechain.constants; -import io.emeraldpay.polkaj.types.Hash256; +import com.limechain.polkaj.Hash256; public class GenesisBlockHash { public static final Hash256 POLKADOT = diff --git a/src/main/java/com/limechain/network/Network.java b/src/main/java/com/limechain/network/Network.java index 08611d41e..d1efb067c 100644 --- a/src/main/java/com/limechain/network/Network.java +++ b/src/main/java/com/limechain/network/Network.java @@ -25,7 +25,7 @@ public class Network { private final Chain chain; @Getter private final String[] bootNodes; -// private final ConnectionManager connectionManager; + // private final ConnectionManager connectionManager; @Getter private KademliaService kademliaService; private boolean started = false; @@ -37,12 +37,12 @@ public class Network { * Manages if nodes running locally are going to be allowed * Connects Kademlia to boot nodes * - * @param chainService chain specification information containing boot nodes - * @param hostConfig host configuration containing current network - * @param repository database repository + * @param chainService chain specification information containing boot nodes + * @param hostConfig host configuration containing current network + * @param repository database repository */ public Network(ChainService chainService, HostConfig hostConfig, KVRepository repository) { - this.bootNodes = null;// chainService.getChainSpec().getBootNodes(); + this.bootNodes = chainService.getChainSpec().getBootNodes(); this.chain = hostConfig.getChain(); // this.connectionManager = ConnectionManager.getInstance(); this.initializeProtocols(chainService, hostConfig, repository); @@ -51,21 +51,15 @@ public Network(ChainService chainService, HostConfig hostConfig, KVRepository repository) { - boolean isLocalEnabled = hostConfig.getChain() == Chain.LOCAL; - boolean clientMode = true; + // -// String pingProtocol = ProtocolUtils.PING_PROTOCOL; // String chainId = chainService.getChainSpec().getProtocolId(); -// String kadProtocolId = ProtocolUtils.getKadProtocol(chainId); // String warpProtocolId = ProtocolUtils.getWarpSyncProtocol(chainId); // String lightProtocolId = ProtocolUtils.getLightMessageProtocol(chainId); -// String syncProtocolId = ProtocolUtils.getSyncProtocol(chainId); -// String stateProtocolId = ProtocolUtils.getStateProtocol(chainId); // String blockAnnounceProtocolId = ProtocolUtils.getBlockAnnounceProtocol(chainId); // String grandpaProtocolId = ProtocolUtils.getGrandpaProtocol(chainId); -// String transactionsProtocolId = ProtocolUtils.getTransactionsProtocol(chainId); -// kademliaService = new KademliaService(kadProtocolId, isLocalEnabled, clientMode); + kademliaService = new KademliaService(); } // private Ed25519PrivateKey loadPrivateKeyFromDB(KVRepository repository) { @@ -85,6 +79,7 @@ private void initializeProtocols(ChainService chainService, public void start() { log.log(Level.INFO, "Starting network module..."); + kademliaService.connectBootNodes(this.bootNodes); started = true; log.log(Level.INFO, "Started network module!"); @@ -161,7 +156,7 @@ public void findPeers() { log.log(Level.INFO, String.format("Connected peers: %s", getPeersCount())); } -// @Scheduled(fixedDelay = 1, timeUnit = TimeUnit.MINUTES) + // @Scheduled(fixedDelay = 1, timeUnit = TimeUnit.MINUTES) public void pingPeers() { // TODO: This needs to by synchronized with the findPeers method if (getPeersCount() == 0) { @@ -259,7 +254,7 @@ public void pingPeers() { // ).start(); // } -// @Scheduled(fixedRate = 5, initialDelay = 5, timeUnit = TimeUnit.MINUTES) + // @Scheduled(fixedRate = 5, initialDelay = 5, timeUnit = TimeUnit.MINUTES) public void sendNeighbourMessages() { if (!AppBean.getBean(WarpSyncState.class).isWarpSyncFinished()) { return; diff --git a/src/main/java/com/limechain/network/dto/PeerInfo.java b/src/main/java/com/limechain/network/dto/PeerInfo.java index 960bf1253..dd5e51140 100644 --- a/src/main/java/com/limechain/network/dto/PeerInfo.java +++ b/src/main/java/com/limechain/network/dto/PeerInfo.java @@ -1,6 +1,6 @@ package com.limechain.network.dto; -import io.emeraldpay.polkaj.types.Hash256; +import com.limechain.polkaj.Hash256; import lombok.Data; import lombok.NoArgsConstructor; diff --git a/src/main/java/com/limechain/network/kad/KademliaService.java b/src/main/java/com/limechain/network/kad/KademliaService.java index d12763448..9ff049188 100644 --- a/src/main/java/com/limechain/network/kad/KademliaService.java +++ b/src/main/java/com/limechain/network/kad/KademliaService.java @@ -1,8 +1,15 @@ package com.limechain.network.kad; +import com.limechain.network.kad.dto.Host; +import com.limechain.network.kad.dto.PeerId; import lombok.Getter; +import lombok.Setter; import lombok.extern.java.Log; +import org.teavm.interop.Async; +import org.teavm.interop.AsyncCallback; +import org.teavm.jso.JSBody; +import java.util.Arrays; import java.util.Random; import java.util.concurrent.ExecutionException; import java.util.logging.Level; @@ -14,30 +21,13 @@ @Log public class KademliaService /*extends NetworkService*/ { public static final int REPLICATION = 20; - private static final int ALPHA = 3; private static final Random RANDOM = new Random(); -// @Setter -// private Host host; -// private List bootNodePeerIds; + @Setter + private Host host; + // private List bootNodePeerIds; private int successfulBootNodes; - public KademliaService(String protocolId, boolean localDht, boolean clientMode) { - this.initialize(protocolId, localDht, clientMode); - } - - /** - * Initializes Kademlia dht with replication=20 and alpha=3 - * - * @param protocolId -// * @param hostId - * @param localEnabled - */ - private void initialize(String protocolId, boolean localEnabled, boolean clientMode) { -// protocol = new Kademlia( -// new KademliaEngine(hostId, new RamProviderStore(1000), new RamRecordStore(), new RamBlockstore()), -// protocolId, REPLICATION, ALPHA, localEnabled, clientMode); - } public void addReservedPeer(String multiaddr) throws ExecutionException, InterruptedException { // final Multiaddr addrWithPeer = Multiaddr.fromString(multiaddr); @@ -61,19 +51,45 @@ public void addReservedPeer(String multiaddr) throws ExecutionException, Interru * @return the number of successfully connected nodes */ public int connectBootNodes(String[] bootNodes) { -// var bootstrapMultiAddress = Arrays.stream(bootNodes) -// .map(DnsUtils::dnsNodeToIp4) -// .map(MultiAddress::new) -// .toList(); -// this.setBootNodePeerIds(bootNodes); -// successfulBootNodes = protocol.bootstrapRoutingTable(host, bootstrapMultiAddress, -// addr -> !addr.contains("wss") && !addr.contains("ws")); + startNetwork(bootNodes); + Object peer = getPeerId(); + while (peer.toString().equalsIgnoreCase("undefined")) { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + peer = getPeerId(); + } + String peerIdStr = peer.toString(); + byte[] privateKey = getPeerPrivateKey(); + byte[] publicKey = getPeerPublicKey(); + + PeerId peerId = new PeerId(privateKey, publicKey, peerIdStr); + this.host = new Host(peerId); + + successfulBootNodes = getPeerStoreSize(); + if (successfulBootNodes > 0) log.log(Level.INFO, "Successfully connected to " + successfulBootNodes + " boot nodes"); else log.log(Level.SEVERE, "Failed to connect to boot nodes"); return successfulBootNodes; } + @JSBody(params = {"bootNodes"}, script = "start(bootNodes)") + @Async + public static native void startNetwork(String[] bootNodes); + + @JSBody(script = "return getPeerId()") + public static native Object getPeerId(); + @JSBody(script = "return libp.peerId.privateKey") + public static native byte[] getPeerPrivateKey(); + @JSBody(script = "return libp.peerId.publicKey") + public static native byte[] getPeerPublicKey(); + @JSBody(script = "return libp.peerStore.store.datastore.data.size") + public static native int getPeerStoreSize(); + + /** * Populates Kademlia dht with peers closest in distance to a random id then makes connections with our node */ diff --git a/src/main/java/com/limechain/network/kad/dto/Host.java b/src/main/java/com/limechain/network/kad/dto/Host.java new file mode 100644 index 000000000..27fa98632 --- /dev/null +++ b/src/main/java/com/limechain/network/kad/dto/Host.java @@ -0,0 +1,12 @@ +package com.limechain.network.kad.dto; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +@AllArgsConstructor +@Getter +@Setter +public class Host { + private PeerId peerId; +} diff --git a/src/main/java/com/limechain/network/kad/dto/PeerId.java b/src/main/java/com/limechain/network/kad/dto/PeerId.java new file mode 100644 index 000000000..c4e13249d --- /dev/null +++ b/src/main/java/com/limechain/network/kad/dto/PeerId.java @@ -0,0 +1,13 @@ +package com.limechain.network.kad.dto; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.teavm.jso.JSObject; + +@AllArgsConstructor +@Getter +public class PeerId implements JSObject { + private byte[] privateKey; + private byte[] publicKey; + private String peerIdStr; +} diff --git a/src/main/java/com/limechain/network/protocol/blockannounce/BlockAnnounceEngine.java b/src/main/java/com/limechain/network/protocol/blockannounce/BlockAnnounceEngine.java index 2246b19e8..b0d08e4c1 100644 --- a/src/main/java/com/limechain/network/protocol/blockannounce/BlockAnnounceEngine.java +++ b/src/main/java/com/limechain/network/protocol/blockannounce/BlockAnnounceEngine.java @@ -8,10 +8,10 @@ import com.limechain.network.protocol.blockannounce.scale.BlockAnnounceHandshakeScaleReader; import com.limechain.network.protocol.blockannounce.scale.BlockAnnounceHandshakeScaleWriter; import com.limechain.network.protocol.blockannounce.scale.BlockAnnounceMessageScaleReader; +import com.limechain.polkaj.reader.ScaleCodecReader; +import com.limechain.polkaj.writer.ScaleCodecWriter; import com.limechain.rpc.server.AppBean; import com.limechain.sync.warpsync.WarpSyncState; -import io.emeraldpay.polkaj.scale.ScaleCodecReader; -import io.emeraldpay.polkaj.scale.ScaleCodecWriter; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.extern.java.Log; diff --git a/src/main/java/com/limechain/network/protocol/blockannounce/messages/BlockAnnounceHandshake.java b/src/main/java/com/limechain/network/protocol/blockannounce/messages/BlockAnnounceHandshake.java index b89f0ee08..5030ee59c 100644 --- a/src/main/java/com/limechain/network/protocol/blockannounce/messages/BlockAnnounceHandshake.java +++ b/src/main/java/com/limechain/network/protocol/blockannounce/messages/BlockAnnounceHandshake.java @@ -1,6 +1,6 @@ package com.limechain.network.protocol.blockannounce.messages; -import io.emeraldpay.polkaj.types.Hash256; +import com.limechain.polkaj.Hash256; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; diff --git a/src/main/java/com/limechain/network/protocol/blockannounce/messages/BlockAnnounceHandshakeBuilder.java b/src/main/java/com/limechain/network/protocol/blockannounce/messages/BlockAnnounceHandshakeBuilder.java index 4f24c8e43..5b87ba856 100644 --- a/src/main/java/com/limechain/network/protocol/blockannounce/messages/BlockAnnounceHandshakeBuilder.java +++ b/src/main/java/com/limechain/network/protocol/blockannounce/messages/BlockAnnounceHandshakeBuilder.java @@ -2,9 +2,9 @@ import com.limechain.config.HostConfig; import com.limechain.network.protocol.blockannounce.NodeRole; +import com.limechain.polkaj.Hash256; import com.limechain.rpc.server.AppBean; import com.limechain.storage.block.SyncState; -import io.emeraldpay.polkaj.types.Hash256; import java.math.BigInteger; diff --git a/src/main/java/com/limechain/network/protocol/blockannounce/scale/BlockAnnounceHandshakeScaleReader.java b/src/main/java/com/limechain/network/protocol/blockannounce/scale/BlockAnnounceHandshakeScaleReader.java index c985b4ca2..50bae0a72 100644 --- a/src/main/java/com/limechain/network/protocol/blockannounce/scale/BlockAnnounceHandshakeScaleReader.java +++ b/src/main/java/com/limechain/network/protocol/blockannounce/scale/BlockAnnounceHandshakeScaleReader.java @@ -1,9 +1,9 @@ package com.limechain.network.protocol.blockannounce.scale; import com.limechain.network.protocol.blockannounce.messages.BlockAnnounceHandshake; -import io.emeraldpay.polkaj.scale.ScaleCodecReader; -import io.emeraldpay.polkaj.scale.ScaleReader; -import io.emeraldpay.polkaj.types.Hash256; +import com.limechain.polkaj.Hash256; +import com.limechain.polkaj.reader.ScaleCodecReader; +import com.limechain.polkaj.reader.ScaleReader; import java.math.BigInteger; diff --git a/src/main/java/com/limechain/network/protocol/blockannounce/scale/BlockAnnounceHandshakeScaleWriter.java b/src/main/java/com/limechain/network/protocol/blockannounce/scale/BlockAnnounceHandshakeScaleWriter.java index 5f0bff887..a108bb1c1 100644 --- a/src/main/java/com/limechain/network/protocol/blockannounce/scale/BlockAnnounceHandshakeScaleWriter.java +++ b/src/main/java/com/limechain/network/protocol/blockannounce/scale/BlockAnnounceHandshakeScaleWriter.java @@ -1,8 +1,8 @@ package com.limechain.network.protocol.blockannounce.scale; import com.limechain.network.protocol.blockannounce.messages.BlockAnnounceHandshake; -import io.emeraldpay.polkaj.scale.ScaleCodecWriter; -import io.emeraldpay.polkaj.scale.ScaleWriter; +import com.limechain.polkaj.writer.ScaleCodecWriter; +import com.limechain.polkaj.writer.ScaleWriter; import java.io.IOException; diff --git a/src/main/java/com/limechain/network/protocol/blockannounce/scale/BlockAnnounceMessageScaleReader.java b/src/main/java/com/limechain/network/protocol/blockannounce/scale/BlockAnnounceMessageScaleReader.java index a15371136..d5309330b 100644 --- a/src/main/java/com/limechain/network/protocol/blockannounce/scale/BlockAnnounceMessageScaleReader.java +++ b/src/main/java/com/limechain/network/protocol/blockannounce/scale/BlockAnnounceMessageScaleReader.java @@ -2,8 +2,8 @@ import com.limechain.network.protocol.blockannounce.messages.BlockAnnounceMessage; import com.limechain.network.protocol.warp.scale.reader.BlockHeaderReader; -import io.emeraldpay.polkaj.scale.ScaleCodecReader; -import io.emeraldpay.polkaj.scale.ScaleReader; +import com.limechain.polkaj.reader.ScaleCodecReader; +import com.limechain.polkaj.reader.ScaleReader; public class BlockAnnounceMessageScaleReader implements ScaleReader { @Override diff --git a/src/main/java/com/limechain/network/protocol/blockannounce/scale/BlockHeaderScaleWriter.java b/src/main/java/com/limechain/network/protocol/blockannounce/scale/BlockHeaderScaleWriter.java index 58c7488e0..143da1f87 100644 --- a/src/main/java/com/limechain/network/protocol/blockannounce/scale/BlockHeaderScaleWriter.java +++ b/src/main/java/com/limechain/network/protocol/blockannounce/scale/BlockHeaderScaleWriter.java @@ -3,9 +3,9 @@ import com.limechain.network.protocol.warp.dto.BlockHeader; import com.limechain.network.protocol.warp.dto.DigestType; import com.limechain.network.protocol.warp.dto.HeaderDigest; -import io.emeraldpay.polkaj.scale.ScaleCodecWriter; -import io.emeraldpay.polkaj.scale.ScaleWriter; -import io.emeraldpay.polkaj.scale.writer.ListWriter; +import com.limechain.polkaj.writer.ListWriter; +import com.limechain.polkaj.writer.ScaleCodecWriter; +import com.limechain.polkaj.writer.ScaleWriter; import lombok.AccessLevel; import lombok.NoArgsConstructor; diff --git a/src/main/java/com/limechain/network/protocol/blockannounce/scale/HeaderDigestScaleWriter.java b/src/main/java/com/limechain/network/protocol/blockannounce/scale/HeaderDigestScaleWriter.java index 364707ed2..8cbd806ff 100644 --- a/src/main/java/com/limechain/network/protocol/blockannounce/scale/HeaderDigestScaleWriter.java +++ b/src/main/java/com/limechain/network/protocol/blockannounce/scale/HeaderDigestScaleWriter.java @@ -2,8 +2,8 @@ import com.limechain.network.protocol.warp.dto.DigestType; import com.limechain.network.protocol.warp.dto.HeaderDigest; -import io.emeraldpay.polkaj.scale.ScaleCodecWriter; -import io.emeraldpay.polkaj.scale.ScaleWriter; +import com.limechain.polkaj.writer.ScaleCodecWriter; +import com.limechain.polkaj.writer.ScaleWriter; import lombok.AccessLevel; import lombok.NoArgsConstructor; diff --git a/src/main/java/com/limechain/network/protocol/grandpa/messages/commit/CommitMessageScaleReader.java b/src/main/java/com/limechain/network/protocol/grandpa/messages/commit/CommitMessageScaleReader.java index fd5e0d2d4..cf385c020 100644 --- a/src/main/java/com/limechain/network/protocol/grandpa/messages/commit/CommitMessageScaleReader.java +++ b/src/main/java/com/limechain/network/protocol/grandpa/messages/commit/CommitMessageScaleReader.java @@ -2,9 +2,9 @@ import com.limechain.exception.scale.WrongMessageTypeException; import com.limechain.network.protocol.grandpa.messages.GrandpaMessageType; -import io.emeraldpay.polkaj.scale.ScaleCodecReader; -import io.emeraldpay.polkaj.scale.ScaleReader; -import io.emeraldpay.polkaj.scale.reader.UInt64Reader; +import com.limechain.polkaj.reader.ScaleCodecReader; +import com.limechain.polkaj.reader.ScaleReader; +import com.limechain.polkaj.reader.UInt64Reader; public class CommitMessageScaleReader implements ScaleReader { diff --git a/src/main/java/com/limechain/network/protocol/grandpa/messages/commit/CommitMessageScaleWriter.java b/src/main/java/com/limechain/network/protocol/grandpa/messages/commit/CommitMessageScaleWriter.java index d4983ae1e..4059ad2fc 100644 --- a/src/main/java/com/limechain/network/protocol/grandpa/messages/commit/CommitMessageScaleWriter.java +++ b/src/main/java/com/limechain/network/protocol/grandpa/messages/commit/CommitMessageScaleWriter.java @@ -1,9 +1,9 @@ package com.limechain.network.protocol.grandpa.messages.commit; import com.limechain.network.protocol.grandpa.messages.GrandpaMessageType; -import io.emeraldpay.polkaj.scale.ScaleCodecWriter; -import io.emeraldpay.polkaj.scale.ScaleWriter; -import io.emeraldpay.polkaj.scale.writer.UInt64Writer; +import com.limechain.polkaj.writer.ScaleCodecWriter; +import com.limechain.polkaj.writer.ScaleWriter; +import com.limechain.polkaj.writer.UInt64Writer; import java.io.IOException; diff --git a/src/main/java/com/limechain/network/protocol/grandpa/messages/commit/CompactJustificationScaleReader.java b/src/main/java/com/limechain/network/protocol/grandpa/messages/commit/CompactJustificationScaleReader.java index 902055277..823faabd4 100644 --- a/src/main/java/com/limechain/network/protocol/grandpa/messages/commit/CompactJustificationScaleReader.java +++ b/src/main/java/com/limechain/network/protocol/grandpa/messages/commit/CompactJustificationScaleReader.java @@ -2,11 +2,11 @@ import com.limechain.exception.network.SignatureCountMismatchException; import com.limechain.network.protocol.warp.dto.Precommit; -import io.emeraldpay.polkaj.scale.ScaleCodecReader; -import io.emeraldpay.polkaj.scale.ScaleReader; -import io.emeraldpay.polkaj.scale.reader.ListReader; -import io.emeraldpay.polkaj.types.Hash256; -import io.emeraldpay.polkaj.types.Hash512; +import com.limechain.polkaj.Hash256; +import com.limechain.polkaj.Hash512; +import com.limechain.polkaj.reader.ListReader; +import com.limechain.polkaj.reader.ScaleCodecReader; +import com.limechain.polkaj.reader.ScaleReader; import java.util.List; diff --git a/src/main/java/com/limechain/network/protocol/grandpa/messages/commit/CompactJustificationScaleWriter.java b/src/main/java/com/limechain/network/protocol/grandpa/messages/commit/CompactJustificationScaleWriter.java index 8cdc6e829..a9e4a4069 100644 --- a/src/main/java/com/limechain/network/protocol/grandpa/messages/commit/CompactJustificationScaleWriter.java +++ b/src/main/java/com/limechain/network/protocol/grandpa/messages/commit/CompactJustificationScaleWriter.java @@ -1,8 +1,8 @@ package com.limechain.network.protocol.grandpa.messages.commit; import com.limechain.network.protocol.warp.dto.Precommit; -import io.emeraldpay.polkaj.scale.ScaleCodecWriter; -import io.emeraldpay.polkaj.scale.ScaleWriter; +import com.limechain.polkaj.writer.ScaleCodecWriter; +import com.limechain.polkaj.writer.ScaleWriter; import java.io.IOException; diff --git a/src/main/java/com/limechain/network/protocol/grandpa/messages/commit/Vote.java b/src/main/java/com/limechain/network/protocol/grandpa/messages/commit/Vote.java index 4257fb0ff..9e8bd7626 100644 --- a/src/main/java/com/limechain/network/protocol/grandpa/messages/commit/Vote.java +++ b/src/main/java/com/limechain/network/protocol/grandpa/messages/commit/Vote.java @@ -1,6 +1,6 @@ package com.limechain.network.protocol.grandpa.messages.commit; -import io.emeraldpay.polkaj.types.Hash256; +import com.limechain.polkaj.Hash256; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; diff --git a/src/main/java/com/limechain/network/protocol/grandpa/messages/commit/VoteScaleReader.java b/src/main/java/com/limechain/network/protocol/grandpa/messages/commit/VoteScaleReader.java index 1977f27ff..6e4755677 100644 --- a/src/main/java/com/limechain/network/protocol/grandpa/messages/commit/VoteScaleReader.java +++ b/src/main/java/com/limechain/network/protocol/grandpa/messages/commit/VoteScaleReader.java @@ -1,9 +1,9 @@ package com.limechain.network.protocol.grandpa.messages.commit; import com.limechain.network.protocol.warp.scale.reader.BlockNumberReader; -import io.emeraldpay.polkaj.scale.ScaleCodecReader; -import io.emeraldpay.polkaj.scale.ScaleReader; -import io.emeraldpay.polkaj.types.Hash256; +import com.limechain.polkaj.Hash256; +import com.limechain.polkaj.reader.ScaleCodecReader; +import com.limechain.polkaj.reader.ScaleReader; public class VoteScaleReader implements ScaleReader { private static final VoteScaleReader INSTANCE = new VoteScaleReader(); diff --git a/src/main/java/com/limechain/network/protocol/grandpa/messages/commit/VoteScaleWriter.java b/src/main/java/com/limechain/network/protocol/grandpa/messages/commit/VoteScaleWriter.java index bd7785c53..c1b73f926 100644 --- a/src/main/java/com/limechain/network/protocol/grandpa/messages/commit/VoteScaleWriter.java +++ b/src/main/java/com/limechain/network/protocol/grandpa/messages/commit/VoteScaleWriter.java @@ -1,8 +1,8 @@ package com.limechain.network.protocol.grandpa.messages.commit; import com.limechain.network.protocol.warp.scale.writer.BlockNumberWriter; -import io.emeraldpay.polkaj.scale.ScaleCodecWriter; -import io.emeraldpay.polkaj.scale.ScaleWriter; +import com.limechain.polkaj.writer.ScaleCodecWriter; +import com.limechain.polkaj.writer.ScaleWriter; import java.io.IOException; diff --git a/src/main/java/com/limechain/network/protocol/grandpa/messages/neighbour/NeighbourMessageScaleReader.java b/src/main/java/com/limechain/network/protocol/grandpa/messages/neighbour/NeighbourMessageScaleReader.java index ec9eca855..4f8ecf671 100644 --- a/src/main/java/com/limechain/network/protocol/grandpa/messages/neighbour/NeighbourMessageScaleReader.java +++ b/src/main/java/com/limechain/network/protocol/grandpa/messages/neighbour/NeighbourMessageScaleReader.java @@ -2,9 +2,9 @@ import com.limechain.exception.scale.WrongMessageTypeException; import com.limechain.network.protocol.grandpa.messages.GrandpaMessageType; -import io.emeraldpay.polkaj.scale.ScaleCodecReader; -import io.emeraldpay.polkaj.scale.ScaleReader; -import io.emeraldpay.polkaj.scale.reader.UInt64Reader; +import com.limechain.polkaj.reader.ScaleCodecReader; +import com.limechain.polkaj.reader.ScaleReader; +import com.limechain.polkaj.reader.UInt64Reader; import java.math.BigInteger; diff --git a/src/main/java/com/limechain/network/protocol/grandpa/messages/neighbour/NeighbourMessageScaleWriter.java b/src/main/java/com/limechain/network/protocol/grandpa/messages/neighbour/NeighbourMessageScaleWriter.java index 4ce2f63bd..8420dfb84 100644 --- a/src/main/java/com/limechain/network/protocol/grandpa/messages/neighbour/NeighbourMessageScaleWriter.java +++ b/src/main/java/com/limechain/network/protocol/grandpa/messages/neighbour/NeighbourMessageScaleWriter.java @@ -1,9 +1,9 @@ package com.limechain.network.protocol.grandpa.messages.neighbour; import com.limechain.network.protocol.grandpa.messages.GrandpaMessageType; -import io.emeraldpay.polkaj.scale.ScaleCodecWriter; -import io.emeraldpay.polkaj.scale.ScaleWriter; -import io.emeraldpay.polkaj.scale.writer.UInt64Writer; +import com.limechain.polkaj.writer.ScaleCodecWriter; +import com.limechain.polkaj.writer.ScaleWriter; +import com.limechain.polkaj.writer.UInt64Writer; import java.io.IOException; diff --git a/src/main/java/com/limechain/network/protocol/warp/dto/BlockHeader.java b/src/main/java/com/limechain/network/protocol/warp/dto/BlockHeader.java index 9ff1bd40a..46633387d 100644 --- a/src/main/java/com/limechain/network/protocol/warp/dto/BlockHeader.java +++ b/src/main/java/com/limechain/network/protocol/warp/dto/BlockHeader.java @@ -1,8 +1,8 @@ package com.limechain.network.protocol.warp.dto; import com.limechain.network.protocol.blockannounce.scale.BlockHeaderScaleWriter; +import com.limechain.polkaj.Hash256; import com.limechain.utils.scale.ScaleUtils; -import io.emeraldpay.polkaj.types.Hash256; import lombok.Getter; import lombok.Setter; diff --git a/src/main/java/com/limechain/network/protocol/warp/dto/Extrinsics.java b/src/main/java/com/limechain/network/protocol/warp/dto/Extrinsics.java index 3321ca638..80bfe1c3d 100644 --- a/src/main/java/com/limechain/network/protocol/warp/dto/Extrinsics.java +++ b/src/main/java/com/limechain/network/protocol/warp/dto/Extrinsics.java @@ -1,7 +1,7 @@ package com.limechain.network.protocol.warp.dto; import com.limechain.exception.scale.ScaleEncodingException; -import io.emeraldpay.polkaj.scale.ScaleCodecWriter; +import com.limechain.polkaj.writer.ScaleCodecWriter; import lombok.Data; import java.io.ByteArrayOutputStream; diff --git a/src/main/java/com/limechain/network/protocol/warp/dto/Justification.java b/src/main/java/com/limechain/network/protocol/warp/dto/Justification.java index a7f2d4e20..2fdeeda65 100644 --- a/src/main/java/com/limechain/network/protocol/warp/dto/Justification.java +++ b/src/main/java/com/limechain/network/protocol/warp/dto/Justification.java @@ -1,6 +1,6 @@ package com.limechain.network.protocol.warp.dto; -import io.emeraldpay.polkaj.types.Hash256; +import com.limechain.polkaj.Hash256; import lombok.Getter; import lombok.Setter; import lombok.extern.java.Log; diff --git a/src/main/java/com/limechain/network/protocol/warp/dto/Precommit.java b/src/main/java/com/limechain/network/protocol/warp/dto/Precommit.java index b60cd26de..b66b3007d 100644 --- a/src/main/java/com/limechain/network/protocol/warp/dto/Precommit.java +++ b/src/main/java/com/limechain/network/protocol/warp/dto/Precommit.java @@ -1,7 +1,7 @@ package com.limechain.network.protocol.warp.dto; -import io.emeraldpay.polkaj.types.Hash256; -import io.emeraldpay.polkaj.types.Hash512; +import com.limechain.polkaj.Hash256; +import com.limechain.polkaj.Hash512; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; diff --git a/src/main/java/com/limechain/network/protocol/warp/dto/WarpSyncRequest.java b/src/main/java/com/limechain/network/protocol/warp/dto/WarpSyncRequest.java index a33f3d2ce..b03fdaed7 100644 --- a/src/main/java/com/limechain/network/protocol/warp/dto/WarpSyncRequest.java +++ b/src/main/java/com/limechain/network/protocol/warp/dto/WarpSyncRequest.java @@ -1,6 +1,6 @@ package com.limechain.network.protocol.warp.dto; -import io.emeraldpay.polkaj.types.Hash256; +import com.limechain.polkaj.Hash256; import lombok.Getter; public class WarpSyncRequest { diff --git a/src/main/java/com/limechain/network/protocol/warp/scale/reader/BlockBodyReader.java b/src/main/java/com/limechain/network/protocol/warp/scale/reader/BlockBodyReader.java index 5a84ca3fe..fb824c58b 100644 --- a/src/main/java/com/limechain/network/protocol/warp/scale/reader/BlockBodyReader.java +++ b/src/main/java/com/limechain/network/protocol/warp/scale/reader/BlockBodyReader.java @@ -2,8 +2,8 @@ import com.limechain.network.protocol.warp.dto.BlockBody; import com.limechain.network.protocol.warp.dto.Extrinsics; -import io.emeraldpay.polkaj.scale.ScaleCodecReader; -import io.emeraldpay.polkaj.scale.ScaleReader; +import com.limechain.polkaj.reader.ScaleCodecReader; +import com.limechain.polkaj.reader.ScaleReader; import lombok.AccessLevel; import lombok.NoArgsConstructor; diff --git a/src/main/java/com/limechain/network/protocol/warp/scale/reader/BlockHeaderReader.java b/src/main/java/com/limechain/network/protocol/warp/scale/reader/BlockHeaderReader.java index 43e2edd12..b40df4c4a 100644 --- a/src/main/java/com/limechain/network/protocol/warp/scale/reader/BlockHeaderReader.java +++ b/src/main/java/com/limechain/network/protocol/warp/scale/reader/BlockHeaderReader.java @@ -2,9 +2,9 @@ import com.limechain.network.protocol.warp.dto.BlockHeader; import com.limechain.network.protocol.warp.dto.HeaderDigest; -import io.emeraldpay.polkaj.scale.ScaleCodecReader; -import io.emeraldpay.polkaj.scale.ScaleReader; -import io.emeraldpay.polkaj.types.Hash256; +import com.limechain.polkaj.Hash256; +import com.limechain.polkaj.reader.ScaleCodecReader; +import com.limechain.polkaj.reader.ScaleReader; import java.math.BigInteger; diff --git a/src/main/java/com/limechain/network/protocol/warp/scale/reader/BlockNumberReader.java b/src/main/java/com/limechain/network/protocol/warp/scale/reader/BlockNumberReader.java index 083e38d25..c44f5e4a8 100644 --- a/src/main/java/com/limechain/network/protocol/warp/scale/reader/BlockNumberReader.java +++ b/src/main/java/com/limechain/network/protocol/warp/scale/reader/BlockNumberReader.java @@ -1,8 +1,8 @@ package com.limechain.network.protocol.warp.scale.reader; import com.limechain.network.protocol.warp.dto.BlockHeader; -import io.emeraldpay.polkaj.scale.ScaleCodecReader; -import io.emeraldpay.polkaj.scale.ScaleReader; +import com.limechain.polkaj.reader.ScaleCodecReader; +import com.limechain.polkaj.reader.ScaleReader; import java.math.BigInteger; diff --git a/src/main/java/com/limechain/network/protocol/warp/scale/reader/HeaderDigestReader.java b/src/main/java/com/limechain/network/protocol/warp/scale/reader/HeaderDigestReader.java index b4cde088b..46ed4d182 100644 --- a/src/main/java/com/limechain/network/protocol/warp/scale/reader/HeaderDigestReader.java +++ b/src/main/java/com/limechain/network/protocol/warp/scale/reader/HeaderDigestReader.java @@ -3,8 +3,8 @@ import com.limechain.network.protocol.warp.dto.ConsensusEngine; import com.limechain.network.protocol.warp.dto.DigestType; import com.limechain.network.protocol.warp.dto.HeaderDigest; -import io.emeraldpay.polkaj.scale.ScaleCodecReader; -import io.emeraldpay.polkaj.scale.ScaleReader; +import com.limechain.polkaj.reader.ScaleCodecReader; +import com.limechain.polkaj.reader.ScaleReader; public class HeaderDigestReader implements ScaleReader { @Override diff --git a/src/main/java/com/limechain/network/protocol/warp/scale/reader/JustificationReader.java b/src/main/java/com/limechain/network/protocol/warp/scale/reader/JustificationReader.java index 5814a0a3a..5964398ca 100644 --- a/src/main/java/com/limechain/network/protocol/warp/scale/reader/JustificationReader.java +++ b/src/main/java/com/limechain/network/protocol/warp/scale/reader/JustificationReader.java @@ -3,10 +3,10 @@ import com.limechain.network.protocol.warp.dto.BlockHeader; import com.limechain.network.protocol.warp.dto.Precommit; import com.limechain.network.protocol.warp.dto.Justification; -import io.emeraldpay.polkaj.scale.ScaleCodecReader; -import io.emeraldpay.polkaj.scale.ScaleReader; -import io.emeraldpay.polkaj.scale.reader.UInt64Reader; -import io.emeraldpay.polkaj.types.Hash256; +import com.limechain.polkaj.Hash256; +import com.limechain.polkaj.reader.ScaleCodecReader; +import com.limechain.polkaj.reader.ScaleReader; +import com.limechain.polkaj.reader.UInt64Reader; public class JustificationReader implements ScaleReader { @Override diff --git a/src/main/java/com/limechain/network/protocol/warp/scale/reader/PrecommitReader.java b/src/main/java/com/limechain/network/protocol/warp/scale/reader/PrecommitReader.java index ca517f39d..c1d0d6f3d 100644 --- a/src/main/java/com/limechain/network/protocol/warp/scale/reader/PrecommitReader.java +++ b/src/main/java/com/limechain/network/protocol/warp/scale/reader/PrecommitReader.java @@ -1,10 +1,10 @@ package com.limechain.network.protocol.warp.scale.reader; import com.limechain.network.protocol.warp.dto.Precommit; -import io.emeraldpay.polkaj.scale.ScaleCodecReader; -import io.emeraldpay.polkaj.scale.ScaleReader; -import io.emeraldpay.polkaj.types.Hash256; -import io.emeraldpay.polkaj.types.Hash512; +import com.limechain.polkaj.Hash256; +import com.limechain.polkaj.Hash512; +import com.limechain.polkaj.reader.ScaleCodecReader; +import com.limechain.polkaj.reader.ScaleReader; public class PrecommitReader implements ScaleReader { @Override diff --git a/src/main/java/com/limechain/network/protocol/warp/scale/reader/VarUint64Reader.java b/src/main/java/com/limechain/network/protocol/warp/scale/reader/VarUint64Reader.java index 7e82d5487..02c19dc79 100644 --- a/src/main/java/com/limechain/network/protocol/warp/scale/reader/VarUint64Reader.java +++ b/src/main/java/com/limechain/network/protocol/warp/scale/reader/VarUint64Reader.java @@ -1,7 +1,7 @@ package com.limechain.network.protocol.warp.scale.reader; -import io.emeraldpay.polkaj.scale.ScaleCodecReader; -import io.emeraldpay.polkaj.scale.ScaleReader; +import com.limechain.polkaj.reader.ScaleCodecReader; +import com.limechain.polkaj.reader.ScaleReader; import java.math.BigInteger; import java.nio.ByteBuffer; diff --git a/src/main/java/com/limechain/network/protocol/warp/scale/reader/WarpSyncFragmentReader.java b/src/main/java/com/limechain/network/protocol/warp/scale/reader/WarpSyncFragmentReader.java index 3ff2c8ce7..3b2ec9bab 100644 --- a/src/main/java/com/limechain/network/protocol/warp/scale/reader/WarpSyncFragmentReader.java +++ b/src/main/java/com/limechain/network/protocol/warp/scale/reader/WarpSyncFragmentReader.java @@ -1,10 +1,8 @@ package com.limechain.network.protocol.warp.scale.reader; import com.limechain.network.protocol.warp.dto.WarpSyncFragment; -import com.limechain.network.protocol.warp.scale.reader.BlockHeaderReader; -import com.limechain.network.protocol.warp.scale.reader.JustificationReader; -import io.emeraldpay.polkaj.scale.ScaleCodecReader; -import io.emeraldpay.polkaj.scale.ScaleReader; +import com.limechain.polkaj.reader.ScaleCodecReader; +import com.limechain.polkaj.reader.ScaleReader; public class WarpSyncFragmentReader implements ScaleReader { @Override diff --git a/src/main/java/com/limechain/network/protocol/warp/scale/reader/WarpSyncResponseScaleReader.java b/src/main/java/com/limechain/network/protocol/warp/scale/reader/WarpSyncResponseScaleReader.java index 45feda770..1e1a607d6 100644 --- a/src/main/java/com/limechain/network/protocol/warp/scale/reader/WarpSyncResponseScaleReader.java +++ b/src/main/java/com/limechain/network/protocol/warp/scale/reader/WarpSyncResponseScaleReader.java @@ -2,8 +2,8 @@ import com.limechain.network.protocol.warp.dto.WarpSyncFragment; import com.limechain.network.protocol.warp.dto.WarpSyncResponse; -import io.emeraldpay.polkaj.scale.ScaleCodecReader; -import io.emeraldpay.polkaj.scale.ScaleReader; +import com.limechain.polkaj.reader.ScaleCodecReader; +import com.limechain.polkaj.reader.ScaleReader; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/com/limechain/network/protocol/warp/scale/writer/BlockBodyWriter.java b/src/main/java/com/limechain/network/protocol/warp/scale/writer/BlockBodyWriter.java index feb075da8..b62c9bfae 100644 --- a/src/main/java/com/limechain/network/protocol/warp/scale/writer/BlockBodyWriter.java +++ b/src/main/java/com/limechain/network/protocol/warp/scale/writer/BlockBodyWriter.java @@ -2,8 +2,8 @@ import com.limechain.network.protocol.warp.dto.BlockBody; import com.limechain.network.protocol.warp.dto.Extrinsics; -import io.emeraldpay.polkaj.scale.ScaleCodecWriter; -import io.emeraldpay.polkaj.scale.ScaleWriter; +import com.limechain.polkaj.writer.ScaleCodecWriter; +import com.limechain.polkaj.writer.ScaleWriter; import lombok.AccessLevel; import lombok.NoArgsConstructor; diff --git a/src/main/java/com/limechain/network/protocol/warp/scale/writer/BlockNumberWriter.java b/src/main/java/com/limechain/network/protocol/warp/scale/writer/BlockNumberWriter.java index f0036c49d..9b1856e30 100644 --- a/src/main/java/com/limechain/network/protocol/warp/scale/writer/BlockNumberWriter.java +++ b/src/main/java/com/limechain/network/protocol/warp/scale/writer/BlockNumberWriter.java @@ -1,8 +1,8 @@ package com.limechain.network.protocol.warp.scale.writer; import com.limechain.network.protocol.warp.dto.BlockHeader; -import io.emeraldpay.polkaj.scale.ScaleCodecWriter; -import io.emeraldpay.polkaj.scale.ScaleWriter; +import com.limechain.polkaj.writer.ScaleCodecWriter; +import com.limechain.polkaj.writer.ScaleWriter; import java.io.IOException; import java.math.BigInteger; diff --git a/src/main/java/com/limechain/network/protocol/warp/scale/writer/VarUint64Writer.java b/src/main/java/com/limechain/network/protocol/warp/scale/writer/VarUint64Writer.java index a09c3f120..05e1c9f18 100644 --- a/src/main/java/com/limechain/network/protocol/warp/scale/writer/VarUint64Writer.java +++ b/src/main/java/com/limechain/network/protocol/warp/scale/writer/VarUint64Writer.java @@ -1,7 +1,7 @@ package com.limechain.network.protocol.warp.scale.writer; -import io.emeraldpay.polkaj.scale.ScaleCodecWriter; -import io.emeraldpay.polkaj.scale.ScaleWriter; +import com.limechain.polkaj.writer.ScaleCodecWriter; +import com.limechain.polkaj.writer.ScaleWriter; import java.io.IOException; import java.math.BigInteger; diff --git a/src/main/java/com/limechain/network/protocol/warp/scale/writer/WarpSyncRequestWriter.java b/src/main/java/com/limechain/network/protocol/warp/scale/writer/WarpSyncRequestWriter.java index 7db7569e4..e770a3bb3 100644 --- a/src/main/java/com/limechain/network/protocol/warp/scale/writer/WarpSyncRequestWriter.java +++ b/src/main/java/com/limechain/network/protocol/warp/scale/writer/WarpSyncRequestWriter.java @@ -1,8 +1,8 @@ package com.limechain.network.protocol.warp.scale.writer; import com.limechain.network.protocol.warp.dto.WarpSyncRequest; -import io.emeraldpay.polkaj.scale.ScaleCodecWriter; -import io.emeraldpay.polkaj.scale.ScaleWriter; +import com.limechain.polkaj.writer.ScaleCodecWriter; +import com.limechain.polkaj.writer.ScaleWriter; import java.io.IOException; diff --git a/src/main/java/com/limechain/polkaj/ByteData.java b/src/main/java/com/limechain/polkaj/ByteData.java new file mode 100644 index 000000000..9b742075c --- /dev/null +++ b/src/main/java/com/limechain/polkaj/ByteData.java @@ -0,0 +1,57 @@ +package com.limechain.polkaj; + +import java.util.Arrays; + +public class ByteData { + + protected final byte[] value; + + public ByteData(byte[] value) { + if (value == null) { + throw new NullPointerException("Value is null"); + } + this.value = value.clone(); + } + + public static ByteData from(String hex) { + byte[] value = FixedBytes.parseHex(hex); + return new ByteData(value); + } + + public static ByteData empty() { + return new ByteData(new byte[0]); + } + + /** + * @return bytes value + */ + public byte[] getBytes() { + //make a copy to ensure immutability + return value.clone(); + } + + public String toString() { + char[] hex = new char[value.length * 2 + 2]; + hex[0] = '0'; + hex[1] = 'x'; + for (int i = 0; i < value.length; i++) { + byte b = value[i]; + hex[2 + i * 2] = Character.forDigit((b & 0xf0) >> 4, 16); + hex[2 + i * 2 + 1] = Character.forDigit(b & 0x0f, 16); + } + return new String(hex); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof ByteData)) return false; + ByteData byteData = (ByteData) o; + return Arrays.equals(value, byteData.value); + } + + @Override + public int hashCode() { + return Arrays.hashCode(value); + } +} \ No newline at end of file diff --git a/src/main/java/com/limechain/polkaj/CompactMode.java b/src/main/java/com/limechain/polkaj/CompactMode.java new file mode 100644 index 000000000..e19df9be1 --- /dev/null +++ b/src/main/java/com/limechain/polkaj/CompactMode.java @@ -0,0 +1,75 @@ +package com.limechain.polkaj; + +import java.math.BigInteger; + +public enum CompactMode { + + SINGLE((byte)0b00), + TWO((byte)0b01), + FOUR((byte)0b10), + BIGINT((byte)0b11); + + private static BigInteger MAX = BigInteger.valueOf(2).pow(536).subtract(BigInteger.valueOf(1)); + + private byte value; + + private CompactMode(byte value) { + this.value = value; + } + + public byte getValue() { + return value; + } + + public static CompactMode byValue(byte value) { + if (value == SINGLE.value) { + return SINGLE; + } else if (value == TWO.value) { + return TWO; + } else if (value == FOUR.value) { + return FOUR; + } else { + return BIGINT; + } + } + + public static CompactMode forNumber(int number) { + return forNumber((long)number); + } + + public static CompactMode forNumber(long number) { + if (number < 0) { + throw new IllegalArgumentException("Negative numbers are not supported"); + } + if (number <= 0x3f) { + return CompactMode.SINGLE; + } else if (number <= 0x3fff) { + return CompactMode.TWO; + } else if (number <= 0x3fffffff) { + return CompactMode.FOUR; + } else { + return CompactMode.BIGINT; + } + } + + public static CompactMode forNumber(BigInteger number) { + if (number.signum() < 0) { + throw new IllegalArgumentException("Negative numbers are not supported"); + } + if (number.compareTo(MAX) > 0) { + throw new IllegalArgumentException("Numbers larger than 2**536-1 are not supported"); + } + if (number.equals(BigInteger.valueOf(0))) { + return CompactMode.SINGLE; + } else if (number.compareTo(BigInteger.valueOf(0x3fffffff)) > 0) { + return CompactMode.BIGINT; + } else if (number.compareTo(BigInteger.valueOf(0x3fff)) > 0) { + return CompactMode.FOUR; + } else if (number.compareTo(BigInteger.valueOf(0x3f)) > 0) { + return CompactMode.TWO; + } else { + return CompactMode.SINGLE; + } + } + +} \ No newline at end of file diff --git a/src/main/java/com/limechain/polkaj/FixedBytes.java b/src/main/java/com/limechain/polkaj/FixedBytes.java new file mode 100644 index 000000000..1c5162768 --- /dev/null +++ b/src/main/java/com/limechain/polkaj/FixedBytes.java @@ -0,0 +1,58 @@ +package com.limechain.polkaj; + +import java.util.Arrays; + +abstract public class FixedBytes extends ByteData { + + protected FixedBytes(byte[] value, int expectedSize) { + super(value); + if (value.length != expectedSize) { + throw new IllegalArgumentException("Value size must be " + expectedSize + "; received: " + value.length); + } + } + + protected static byte[] parseHex(String hex, int expectedSize) { + if (hex.length() == expectedSize * 2 + 2 && hex.startsWith("0x")) { + hex = hex.substring(2); + } + if (hex.length() != expectedSize * 2) { + throw new IllegalArgumentException("Invalid hex size: " + hex.length()); + } + return parseHex(hex); + } + + protected static byte[] parseHex(String hex) { + if (hex == null) { + throw new NullPointerException("Hex value is null"); + } + if (hex.startsWith("0x")) { + hex = hex.substring(2); + } + int len = hex.length(); + if (len % 2 != 0) { + throw new NumberFormatException("Not event number of digits provided"); + } + byte[] data = new byte[len / 2]; + for (int i = 0; i < len; i += 2) { + data[i / 2] = Integer.valueOf(hex.substring(i, i+2), 16).byteValue(); + } + return data; + } + + @Override + public int hashCode() { + return Arrays.hashCode(value); + } + + protected int compareTo(FixedBytes o) { + if (value.length != o.value.length) { + throw new IllegalStateException("Different size " + value.length + " != " + o.value.length); + } + for (int i = 0; i < value.length; i++) { + if (value[i] != o.value[i]) { + return value[i] - o.value[i]; + } + } + return 0; + } +} \ No newline at end of file diff --git a/src/main/java/com/limechain/polkaj/Hash256.java b/src/main/java/com/limechain/polkaj/Hash256.java new file mode 100644 index 000000000..cf7f5a76d --- /dev/null +++ b/src/main/java/com/limechain/polkaj/Hash256.java @@ -0,0 +1,48 @@ +package com.limechain.polkaj; + + +public class Hash256 extends FixedBytes implements Comparable { + + /** + * Length in bytes (32 byte) + */ + public static final int SIZE_BYTES = 32; + + /** + * Create a new value. Makes sure the input is correct, if not throws an exception + * + * @param value 32 byte value + * @throws NullPointerException if value is null + * @throws IllegalArgumentException is size is not 32 bytes + */ + public Hash256(byte[] value) { + super(value, SIZE_BYTES); + } + + /** + * Creates an empty zeroed instance + * + * @return empty hash + */ + public static Hash256 empty() { + return new Hash256(new byte[SIZE_BYTES]); + } + + /** + * Parse hex value and create a new instance + * + * @param hex hex value, may optionally start with 0x prefix + * @return hash instance + * @throws IllegalArgumentException if value has invalid length + * @throws NumberFormatException if value has invalid format (non-hex characters, etc) + */ + public static Hash256 from(String hex) { + byte[] parsed = parseHex(hex, SIZE_BYTES); + return new Hash256(parsed); + } + + @Override + public int compareTo(Hash256 o) { + return super.compareTo(o); + } +} \ No newline at end of file diff --git a/src/main/java/com/limechain/polkaj/Hash512.java b/src/main/java/com/limechain/polkaj/Hash512.java new file mode 100644 index 000000000..eb549e3a3 --- /dev/null +++ b/src/main/java/com/limechain/polkaj/Hash512.java @@ -0,0 +1,47 @@ +package com.limechain.polkaj; + +public class Hash512 extends FixedBytes implements Comparable { + + /** + * Length in bytes (64 byte) + */ + public static final int SIZE_BYTES = 64; + + /** + * Create a new value. Makes sure the input is correct, if not throws an exception + * + * @param value 64 byte value + * @throws NullPointerException if value is null + * @throws IllegalArgumentException is size is not 64 bytes + */ + public Hash512(byte[] value) { + super(value, SIZE_BYTES); + } + + /** + * Creates an empty zeroed instance + * + * @return empty hash + */ + public static Hash512 empty() { + return new Hash512(new byte[SIZE_BYTES]); + } + + /** + * Parse hex value and create a new instance + * + * @param hex hex value, may optionally start with 0x prefix + * @return hash instance + * @throws IllegalArgumentException if value has invalid length + * @throws NumberFormatException if value has invalid format (non-hex characters, etc) + */ + public static Hash512 from(String hex) { + byte[] parsed = parseHex(hex, SIZE_BYTES); + return new Hash512(parsed); + } + + @Override + public int compareTo(Hash512 o) { + return super.compareTo(o); + } +} \ No newline at end of file diff --git a/src/main/java/com/limechain/polkaj/reader/BoolOptionalReader.java b/src/main/java/com/limechain/polkaj/reader/BoolOptionalReader.java new file mode 100644 index 000000000..869520d95 --- /dev/null +++ b/src/main/java/com/limechain/polkaj/reader/BoolOptionalReader.java @@ -0,0 +1,20 @@ +package com.limechain.polkaj.reader; + +import java.util.Optional; + +public class BoolOptionalReader implements ScaleReader> { + @Override + public Optional read(ScaleCodecReader rdr) { + byte b = rdr.readByte(); + if (b == 0) { + return Optional.empty(); + } + if (b == 1) { + return Optional.of(false); + } + if (b == 2) { + return Optional.of(true); + } + throw new IllegalStateException("Not a boolean option: " + b); + } +} \ No newline at end of file diff --git a/src/main/java/com/limechain/polkaj/reader/BoolReader.java b/src/main/java/com/limechain/polkaj/reader/BoolReader.java new file mode 100644 index 000000000..f14442dee --- /dev/null +++ b/src/main/java/com/limechain/polkaj/reader/BoolReader.java @@ -0,0 +1,15 @@ +package com.limechain.polkaj.reader; + +public class BoolReader implements ScaleReader { + @Override + public Boolean read(ScaleCodecReader rdr) { + byte b = rdr.readByte(); + if (b == 0) { + return false; + } + if (b == 1) { + return true; + } + throw new IllegalStateException("Not a boolean value: " + b); + } +} \ No newline at end of file diff --git a/src/main/java/com/limechain/polkaj/reader/CompactBigIntReader.java b/src/main/java/com/limechain/polkaj/reader/CompactBigIntReader.java new file mode 100644 index 000000000..253f87c30 --- /dev/null +++ b/src/main/java/com/limechain/polkaj/reader/CompactBigIntReader.java @@ -0,0 +1,31 @@ +package com.limechain.polkaj.reader; + +import com.limechain.polkaj.CompactMode; + +import java.math.BigInteger; + +public class CompactBigIntReader implements ScaleReader { + + private static final CompactUIntReader intReader = new CompactUIntReader(); + + @Override + public BigInteger read(ScaleCodecReader rdr) { + int type = rdr.readUByte(); + CompactMode mode = CompactMode.byValue((byte)(type & 0b11)); + if (mode != CompactMode.BIGINT) { + rdr.skip(-1); + int value = intReader.read(rdr); + return BigInteger.valueOf(value); + } + int len = (type >> 2) + 4; + byte[] value = rdr.readByteArray(len); + //LE encoded, so need to reverse it + for (int i = 0; i < value.length / 2; i++) { + byte temp = value[i]; + value[i] = value[value.length -i -1]; + value[value.length - i - 1] = temp; + } + //unsigned, i.e. always positive, signum=1 + return new BigInteger(1, value); + } +} \ No newline at end of file diff --git a/src/main/java/com/limechain/polkaj/reader/CompactUIntReader.java b/src/main/java/com/limechain/polkaj/reader/CompactUIntReader.java new file mode 100644 index 000000000..d5283c502 --- /dev/null +++ b/src/main/java/com/limechain/polkaj/reader/CompactUIntReader.java @@ -0,0 +1,32 @@ +package com.limechain.polkaj.reader; + +import com.limechain.polkaj.CompactMode; + +public class CompactUIntReader implements ScaleReader { + + /** + * + * @param rdr reader with the encoded data + * @return integer value + * @throws UnsupportedOperationException if the value is encoded with more than four bytes (use {@link CompactBigIntReader}) + */ + @Override + public Integer read(ScaleCodecReader rdr) { + int i = rdr.readUByte(); + CompactMode mode = CompactMode.byValue((byte)(i & 0b11)); + if (mode == CompactMode.SINGLE) { + return i >> 2; + } + if (mode == CompactMode.TWO) { + return (i >> 2) + + (rdr.readUByte() << 6); + } + if (mode == CompactMode.FOUR) { + return (i >> 2) + + (rdr.readUByte() << 6) + + (rdr.readUByte() << (6 + 8)) + + (rdr.readUByte() << (6 + 2 * 8)); + } + throw new UnsupportedOperationException("Mode " + mode + " is not implemented"); + } +} \ No newline at end of file diff --git a/src/main/java/com/limechain/polkaj/reader/Int32Reader.java b/src/main/java/com/limechain/polkaj/reader/Int32Reader.java new file mode 100644 index 000000000..f128e1e34 --- /dev/null +++ b/src/main/java/com/limechain/polkaj/reader/Int32Reader.java @@ -0,0 +1,16 @@ +package com.limechain.polkaj.reader; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public class Int32Reader implements ScaleReader { + @Override + public Integer read(ScaleCodecReader rdr) { + ByteBuffer buf = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN); + buf.put(rdr.readByte()); + buf.put(rdr.readByte()); + buf.put(rdr.readByte()); + buf.put(rdr.readByte()); + return buf.flip().getInt(); + } +} \ No newline at end of file diff --git a/src/main/java/com/limechain/polkaj/reader/ListReader.java b/src/main/java/com/limechain/polkaj/reader/ListReader.java new file mode 100644 index 000000000..371174565 --- /dev/null +++ b/src/main/java/com/limechain/polkaj/reader/ListReader.java @@ -0,0 +1,23 @@ +package com.limechain.polkaj.reader; + +import java.util.ArrayList; +import java.util.List; + +public class ListReader implements ScaleReader> { + + private ScaleReader scaleReader; + + public ListReader(ScaleReader scaleReader) { + this.scaleReader = scaleReader; + } + + @Override + public List read(ScaleCodecReader rdr) { + int size = rdr.readCompactInt(); + List result = new ArrayList<>(size); + for (int i = 0; i < size; i++) { + result.add(rdr.read(scaleReader)); + } + return result; + } +} \ No newline at end of file diff --git a/src/main/java/com/limechain/polkaj/reader/ScaleCodecReader.java b/src/main/java/com/limechain/polkaj/reader/ScaleCodecReader.java new file mode 100644 index 000000000..7ab6c8d3c --- /dev/null +++ b/src/main/java/com/limechain/polkaj/reader/ScaleCodecReader.java @@ -0,0 +1,150 @@ +package com.limechain.polkaj.reader; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Optional; + +public class ScaleCodecReader { + + public static final UByteReader UBYTE = new UByteReader(); + public static final UInt16Reader UINT16 = new UInt16Reader(); + public static final UInt32Reader UINT32 = new UInt32Reader(); + public static final UInt128Reader UINT128 = new UInt128Reader(); + public static final Int32Reader INT32 = new Int32Reader(); + public static final CompactUIntReader COMPACT_UINT = new CompactUIntReader(); + public static final CompactBigIntReader COMPACT_BIGINT = new CompactBigIntReader(); + public static final BoolReader BOOL = new BoolReader(); + public static final BoolOptionalReader BOOL_OPTIONAL = new BoolOptionalReader(); + public static final StringReader STRING = new StringReader(); + + private byte[] source; + private int pos = 0; + + public ScaleCodecReader(byte[] source) { + this.source = source; + } + + /** + * + * @return true if has more elements + */ + public boolean hasNext() { + return pos < source.length; + } + + /** + * Move reader position forward (or backward for negative value) + * @param len amount to bytes to skip + */ + public void skip(int len) { + if (len < 0 && Math.abs(len) > pos) { + throw new IllegalArgumentException("Position cannot be negative: " + pos + " " + len); + } + pos += len; + } + + /** + * Specify a new position + * @param pos position + */ + public void seek(int pos) { + if (pos < 0) { + throw new IllegalArgumentException("Position cannot be negative: " + pos); + } else if (pos >= source.length) { + throw new IllegalArgumentException("Position " + pos + " must be strictly smaller than source length: " + source.length); + } + + this.pos = pos; + } + + /** + * @return a next single byte from reader + */ + public byte readByte() { + if (!hasNext()) { + throw new IndexOutOfBoundsException("Cannot read " + pos + " of " + source.length); + } + return source[pos++]; + } + + /** + * Read complex value from the reader + * @param scaleReader reader implementation + * @param resulting type + * @return read value + */ + public T read(ScaleReader scaleReader) { + if (scaleReader == null) { + throw new NullPointerException("ItemReader cannot be null"); + } + return scaleReader.read(this); + } + + public int readUByte() { + return UBYTE.read(this); + } + + public int readUint16() { + return UINT16.read(this); + } + + public long readUint32() { + return UINT32.read(this); + } + + public BigInteger readUint128() { + return UINT128.read(this); + } + + public int readCompactInt() { + return COMPACT_UINT.read(this); + } + + public boolean readBoolean() { + return BOOL.read(this); + } + + /** + * Read optional value from the reader + * @param scaleReader reader implementation + * @param resulting type + * @return optional read value + */ + @SuppressWarnings("unchecked") + public Optional readOptional(ScaleReader scaleReader) { + if (scaleReader instanceof BoolReader || scaleReader instanceof BoolOptionalReader) { + return (Optional) BOOL_OPTIONAL.read(this); + } + boolean some = readBoolean(); + if (some) { + return Optional.of(read(scaleReader)); + } else { + return Optional.empty(); + } + } + + public byte[] readUint256() { + return readByteArray(32); + } + + public byte[] readByteArray() { + int len = readCompactInt(); + return readByteArray(len); + } + + public byte[] readByteArray(int len) { +// byte[] result = new byte[len]; + byte[] result = Arrays.copyOfRange(source, pos, pos + len); +// System.arraycopy(source, pos, result, 0, result.length); + pos += len; + return result; + } + + /** + * Read string, encoded as UTF-8 bytes + * @return string value + */ + public String readString() { + return new String(readByteArray()); + } +} \ No newline at end of file diff --git a/src/main/java/com/limechain/polkaj/reader/ScaleReader.java b/src/main/java/com/limechain/polkaj/reader/ScaleReader.java new file mode 100644 index 000000000..1dbf92294 --- /dev/null +++ b/src/main/java/com/limechain/polkaj/reader/ScaleReader.java @@ -0,0 +1,13 @@ +package com.limechain.polkaj.reader; + +public interface ScaleReader { + + /** + * Reads value from specified reader. The reader must be positioned on the beginning of the value + * + * @param rdr reader with the encoded data + * @return read value + */ + T read(ScaleCodecReader rdr); + +} \ No newline at end of file diff --git a/src/main/java/com/limechain/polkaj/reader/StringReader.java b/src/main/java/com/limechain/polkaj/reader/StringReader.java new file mode 100644 index 000000000..fdb374fd0 --- /dev/null +++ b/src/main/java/com/limechain/polkaj/reader/StringReader.java @@ -0,0 +1,8 @@ +package com.limechain.polkaj.reader; + +public class StringReader implements ScaleReader { + @Override + public String read(ScaleCodecReader rdr) { + return rdr.readString(); + } +} \ No newline at end of file diff --git a/src/main/java/com/limechain/polkaj/reader/UByteReader.java b/src/main/java/com/limechain/polkaj/reader/UByteReader.java new file mode 100644 index 000000000..616f04517 --- /dev/null +++ b/src/main/java/com/limechain/polkaj/reader/UByteReader.java @@ -0,0 +1,12 @@ +package com.limechain.polkaj.reader; + +public class UByteReader implements ScaleReader { + @Override + public Integer read(ScaleCodecReader rdr) { + byte x = rdr.readByte(); + if (x < 0) { + return 256 + (int)x; + } + return (int)x; + } +} \ No newline at end of file diff --git a/src/main/java/com/limechain/polkaj/reader/UInt128Reader.java b/src/main/java/com/limechain/polkaj/reader/UInt128Reader.java new file mode 100644 index 000000000..e84599d4c --- /dev/null +++ b/src/main/java/com/limechain/polkaj/reader/UInt128Reader.java @@ -0,0 +1,24 @@ +package com.limechain.polkaj.reader; + +import java.math.BigInteger; + +public class UInt128Reader implements ScaleReader { + + public static final int SIZE_BYTES = 16; + + public static void reverse(byte[] value) { + for (int i = 0; i < value.length / 2; i++) { + int other = value.length - i - 1; + byte tmp = value[other]; + value[other] = value[i]; + value[i] = tmp; + } + } + + @Override + public BigInteger read(ScaleCodecReader rdr) { + byte[] value = rdr.readByteArray(SIZE_BYTES); + reverse(value); + return new BigInteger(1, value); + } +} \ No newline at end of file diff --git a/src/main/java/com/limechain/polkaj/reader/UInt16Reader.java b/src/main/java/com/limechain/polkaj/reader/UInt16Reader.java new file mode 100644 index 000000000..ed05ca968 --- /dev/null +++ b/src/main/java/com/limechain/polkaj/reader/UInt16Reader.java @@ -0,0 +1,13 @@ +package com.limechain.polkaj.reader; + +public class UInt16Reader implements ScaleReader { + + @Override + public Integer read(ScaleCodecReader rdr) { + int result = 0; + result += rdr.readUByte(); + result += rdr.readUByte() << 8; + return result; + } + +} \ No newline at end of file diff --git a/src/main/java/com/limechain/polkaj/reader/UInt32Reader.java b/src/main/java/com/limechain/polkaj/reader/UInt32Reader.java new file mode 100644 index 000000000..c2c7d67ce --- /dev/null +++ b/src/main/java/com/limechain/polkaj/reader/UInt32Reader.java @@ -0,0 +1,13 @@ +package com.limechain.polkaj.reader; + +public class UInt32Reader implements ScaleReader { + @Override + public Long read(ScaleCodecReader rdr) { + long result = 0; + result += (long)rdr.readUByte(); + result += ((long)rdr.readUByte()) << 8; + result += ((long)rdr.readUByte()) << (2 * 8); + result += ((long)rdr.readUByte()) << (3 * 8); + return result; + } +} \ No newline at end of file diff --git a/src/main/java/com/limechain/polkaj/reader/UInt64Reader.java b/src/main/java/com/limechain/polkaj/reader/UInt64Reader.java new file mode 100644 index 000000000..aa808fb84 --- /dev/null +++ b/src/main/java/com/limechain/polkaj/reader/UInt64Reader.java @@ -0,0 +1,20 @@ +package com.limechain.polkaj.reader; + +import java.math.BigInteger; + +public class UInt64Reader implements ScaleReader { + + @Override + public BigInteger read(ScaleCodecReader rdr) { + BigInteger result = BigInteger.valueOf(0); + result = result.add(BigInteger.valueOf(rdr.readUByte())); + result = result.add(BigInteger.valueOf(rdr.readUByte()).shiftLeft(8)); + result = result.add(BigInteger.valueOf(rdr.readUByte()).shiftLeft(16)); + result = result.add(BigInteger.valueOf(rdr.readUByte()).shiftLeft(24)); + result = result.add(BigInteger.valueOf(rdr.readUByte()).shiftLeft(32)); + result = result.add(BigInteger.valueOf(rdr.readUByte()).shiftLeft(40)); + result = result.add(BigInteger.valueOf(rdr.readUByte()).shiftLeft(48)); + result = result.add(BigInteger.valueOf(rdr.readUByte()).shiftLeft(56)); + return result; + } +} \ No newline at end of file diff --git a/src/main/java/com/limechain/polkaj/writer/BoolOptionalWriter.java b/src/main/java/com/limechain/polkaj/writer/BoolOptionalWriter.java new file mode 100644 index 000000000..9d2ca49cb --- /dev/null +++ b/src/main/java/com/limechain/polkaj/writer/BoolOptionalWriter.java @@ -0,0 +1,18 @@ +package com.limechain.polkaj.writer; + +import java.io.IOException; +import java.util.Optional; + +public class BoolOptionalWriter implements ScaleWriter> { + + @Override + public void write(ScaleCodecWriter wrt, Optional value) throws IOException { + if (value.isEmpty()) { + wrt.directWrite(0); + } else if (value.get()) { + wrt.directWrite(2); + } else { + wrt.directWrite(1); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/limechain/polkaj/writer/BoolWriter.java b/src/main/java/com/limechain/polkaj/writer/BoolWriter.java new file mode 100644 index 000000000..58defda16 --- /dev/null +++ b/src/main/java/com/limechain/polkaj/writer/BoolWriter.java @@ -0,0 +1,14 @@ +package com.limechain.polkaj.writer; + +import java.io.IOException; + +public class BoolWriter implements ScaleWriter { + @Override + public void write(ScaleCodecWriter wrt, Boolean value) throws IOException { + if (value) { + wrt.directWrite(1); + } else { + wrt.directWrite(0); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/limechain/polkaj/writer/CompactUIntWriter.java b/src/main/java/com/limechain/polkaj/writer/CompactUIntWriter.java new file mode 100644 index 000000000..749783cb2 --- /dev/null +++ b/src/main/java/com/limechain/polkaj/writer/CompactUIntWriter.java @@ -0,0 +1,35 @@ +package com.limechain.polkaj.writer; + +import com.limechain.polkaj.CompactMode; + +import java.io.IOException; + +public class CompactUIntWriter implements ScaleWriter { + + @Override + public void write(ScaleCodecWriter wrt, Integer value) throws IOException { + CompactMode mode = CompactMode.forNumber(value); + int compact; + int bytes; + if (mode == CompactMode.BIGINT) { + wrt.directWrite(mode.getValue()); + compact = value; + bytes = 4; + } else { + compact = (value << 2) + mode.getValue(); + if (mode == CompactMode.SINGLE) { + bytes = 1; + } else if (mode == CompactMode.TWO) { + bytes = 2; + } else { + bytes = 4; + } + } + while (bytes > 0) { + wrt.directWrite(compact & 0xff); + compact >>= 8; + bytes--; + } + } + +} \ No newline at end of file diff --git a/src/main/java/com/limechain/polkaj/writer/ListWriter.java b/src/main/java/com/limechain/polkaj/writer/ListWriter.java new file mode 100644 index 000000000..90a59cf84 --- /dev/null +++ b/src/main/java/com/limechain/polkaj/writer/ListWriter.java @@ -0,0 +1,21 @@ +package com.limechain.polkaj.writer; + +import java.io.IOException; +import java.util.List; + +public class ListWriter implements ScaleWriter> { + + private ScaleWriter scaleWriter; + + public ListWriter(ScaleWriter scaleWriter) { + this.scaleWriter = scaleWriter; + } + + @Override + public void write(ScaleCodecWriter wrt, List value) throws IOException { + wrt.writeCompact(value.size()); + for (T item: value) { + scaleWriter.write(wrt, item); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/limechain/polkaj/writer/ScaleCodecWriter.java b/src/main/java/com/limechain/polkaj/writer/ScaleCodecWriter.java new file mode 100644 index 000000000..3edc2ff24 --- /dev/null +++ b/src/main/java/com/limechain/polkaj/writer/ScaleCodecWriter.java @@ -0,0 +1,131 @@ +package com.limechain.polkaj.writer; + +import java.io.Closeable; +import java.io.IOException; +import java.io.OutputStream; +import java.math.BigInteger; +import java.util.Optional; + +public class ScaleCodecWriter implements Closeable { + + public static final CompactUIntWriter COMPACT_UINT = new CompactUIntWriter(); + public static final UInt16Writer UINT16 = new UInt16Writer(); + public static final UInt32Writer UINT32 = new UInt32Writer(); + public static final UInt128Writer UINT128 = new UInt128Writer(); + public static final ULong32Writer ULONG32 = new ULong32Writer(); + public static final BoolWriter BOOL = new BoolWriter(); + public static final BoolOptionalWriter BOOL_OPT = new BoolOptionalWriter(); + + private final OutputStream out; + + public ScaleCodecWriter(OutputStream out) { + this.out = out; + } + + public void writeUint256(byte[] value) throws IOException { + if (value.length != 32) { + throw new IllegalArgumentException("Value must be 32 byte array"); + } + writeByteArray(value); + } + + public void writeByteArray(byte[] value) throws IOException { + out.write(value, 0, value.length); + } + + public void writeAsList(byte[] value) throws IOException { + writeCompact(value.length); + out.write(value, 0, value.length); + } + + /** + * Write the byte into output stream as-is directly, the input is supposed to be already encoded + * + * @param b byte to write + * @throws IOException if failed to write + */ + public void directWrite(int b) throws IOException { + out.write(b); + } + + /** + * Write the bytes into output stream as-is directly, the input is supposed to be already encoded + * + * @param b bytes to write + * @param off offset + * @param len length + * @throws IOException if failed to write + */ + public void directWrite(byte[] b, int off, int len) throws IOException { + out.write(b, off, len); + } + + public void flush() throws IOException { + out.flush(); + } + + @Override + public void close() throws IOException { + out.close(); + } + + public void write(ScaleWriter writer, T value) throws IOException { + writer.write(this, value); + } + + public void writeByte(int value) throws IOException { + directWrite(value); + } + + public void writeByte(byte value) throws IOException { + directWrite(value); + } + + public void writeUint16(int value) throws IOException { + UINT16.write(this, value); + } + + public void writeUint32(int value) throws IOException { + UINT32.write(this, value); + } + + public void writeUint32(long value) throws IOException { + ULONG32.write(this, value); + } + + public void writeUint128(BigInteger value) throws IOException { + UINT128.write(this, value); + } + + public void writeCompact(int value) throws IOException { + COMPACT_UINT.write(this, value); + } + + @SuppressWarnings("unchecked") + public void writeOptional(ScaleWriter writer, T value) throws IOException { + if (writer instanceof BoolOptionalWriter || writer instanceof BoolWriter) { + BOOL_OPT.write(this, (Optional) Optional.ofNullable(value)); + } else { + if (value == null) { + BOOL.write(this, false); + } else { + BOOL.write(this, true); + writer.write(this, value); + } + } + } + + @SuppressWarnings("unchecked") + public void writeOptional(ScaleWriter writer, Optional value) throws IOException { + if (writer instanceof BoolOptionalWriter || writer instanceof BoolWriter) { + BOOL_OPT.write(this, (Optional) value); + } else { + if (value.isEmpty()) { + BOOL.write(this, false); + } else { + BOOL.write(this, true); + writer.write(this, value.get()); + } + } + } +} \ No newline at end of file diff --git a/src/main/java/com/limechain/polkaj/writer/ScaleWriter.java b/src/main/java/com/limechain/polkaj/writer/ScaleWriter.java new file mode 100644 index 000000000..574b8812a --- /dev/null +++ b/src/main/java/com/limechain/polkaj/writer/ScaleWriter.java @@ -0,0 +1,7 @@ +package com.limechain.polkaj.writer; + +import java.io.IOException; + +public interface ScaleWriter { + void write(ScaleCodecWriter wrt, T value) throws IOException; +} \ No newline at end of file diff --git a/src/main/java/com/limechain/polkaj/writer/UInt128Writer.java b/src/main/java/com/limechain/polkaj/writer/UInt128Writer.java new file mode 100644 index 000000000..8828586df --- /dev/null +++ b/src/main/java/com/limechain/polkaj/writer/UInt128Writer.java @@ -0,0 +1,30 @@ +package com.limechain.polkaj.writer; + +import com.limechain.polkaj.reader.UInt128Reader; + +import java.io.IOException; +import java.math.BigInteger; + +public class UInt128Writer implements ScaleWriter { + + @Override + public void write(ScaleCodecWriter wrt, BigInteger value) throws IOException { + if (value.signum() < 0) { + throw new IllegalArgumentException("Negative numbers are not supported by Uint128"); + } + byte[] array = value.toByteArray(); + int pos = 0; + // sometimes BigInteger gives an extra zero byte in the start of the array + if (array[0] == 0) { + pos++; + } + int len = array.length - pos; + if (len > UInt128Reader.SIZE_BYTES) { + throw new IllegalArgumentException("Value is to big for 128 bits. Has: " + len * 8 + " bits"); + } + byte[] encoded = new byte[UInt128Reader.SIZE_BYTES]; + System.arraycopy(array, pos, encoded, encoded.length - len, len); + UInt128Reader.reverse(encoded); + wrt.directWrite(encoded, 0, UInt128Reader.SIZE_BYTES); + } +} \ No newline at end of file diff --git a/src/main/java/com/limechain/polkaj/writer/UInt16Writer.java b/src/main/java/com/limechain/polkaj/writer/UInt16Writer.java new file mode 100644 index 000000000..58eca5845 --- /dev/null +++ b/src/main/java/com/limechain/polkaj/writer/UInt16Writer.java @@ -0,0 +1,11 @@ +package com.limechain.polkaj.writer; + +import java.io.IOException; + +public class UInt16Writer implements ScaleWriter { + @Override + public void write(ScaleCodecWriter wrt, Integer value) throws IOException { + wrt.directWrite(value & 0xff); + wrt.directWrite((value >> 8) & 0xff); + } +} \ No newline at end of file diff --git a/src/main/java/com/limechain/polkaj/writer/UInt32Writer.java b/src/main/java/com/limechain/polkaj/writer/UInt32Writer.java new file mode 100644 index 000000000..f2a974ed2 --- /dev/null +++ b/src/main/java/com/limechain/polkaj/writer/UInt32Writer.java @@ -0,0 +1,16 @@ +package com.limechain.polkaj.writer; + +import java.io.IOException; + +public class UInt32Writer implements ScaleWriter { + @Override + public void write(ScaleCodecWriter wrt, Integer value) throws IOException { + if (value < 0) { + throw new IllegalArgumentException("Negative values are not supported: " + value); + } + wrt.directWrite(value & 0xff); + wrt.directWrite((value >> 8) & 0xff); + wrt.directWrite((value >> 16) & 0xff); + wrt.directWrite((value >> 24) & 0xff); + } +} \ No newline at end of file diff --git a/src/main/java/com/limechain/polkaj/writer/UInt64Writer.java b/src/main/java/com/limechain/polkaj/writer/UInt64Writer.java new file mode 100644 index 000000000..c97a3db7e --- /dev/null +++ b/src/main/java/com/limechain/polkaj/writer/UInt64Writer.java @@ -0,0 +1,27 @@ +package com.limechain.polkaj.writer; + +import java.io.IOException; +import java.math.BigInteger; + +public class UInt64Writer implements ScaleWriter { + + public static final BigInteger MAX_UINT64 = new BigInteger("18446744073709551615"); + + @Override + public void write(ScaleCodecWriter wrt, BigInteger value) throws IOException { + if (value.compareTo(BigInteger.valueOf(0)) < 0) { + throw new IllegalArgumentException("Negative values are not supported: " + value); + } + if (value.compareTo(MAX_UINT64) > 0) { + throw new IllegalArgumentException("Value is to big for 64 bits. " + value); + } + wrt.directWrite(value.and(BigInteger.valueOf(255)).intValue()); + wrt.directWrite(value.shiftRight(8).and(BigInteger.valueOf(255)).intValue()); + wrt.directWrite(value.shiftRight(16).and(BigInteger.valueOf(255)).intValue()); + wrt.directWrite(value.shiftRight(24).and(BigInteger.valueOf(255)).intValue()); + wrt.directWrite(value.shiftRight(32).and(BigInteger.valueOf(255)).intValue()); + wrt.directWrite(value.shiftRight(40).and(BigInteger.valueOf(255)).intValue()); + wrt.directWrite(value.shiftRight(48).and(BigInteger.valueOf(255)).intValue()); + wrt.directWrite(value.shiftRight(56).and(BigInteger.valueOf(255)).intValue()); + } +} \ No newline at end of file diff --git a/src/main/java/com/limechain/polkaj/writer/ULong32Writer.java b/src/main/java/com/limechain/polkaj/writer/ULong32Writer.java new file mode 100644 index 000000000..f75e7e817 --- /dev/null +++ b/src/main/java/com/limechain/polkaj/writer/ULong32Writer.java @@ -0,0 +1,19 @@ +package com.limechain.polkaj.writer; + +import java.io.IOException; + +public class ULong32Writer implements ScaleWriter { + @Override + public void write(ScaleCodecWriter wrt, Long value) throws IOException { + if (value < 0) { + throw new IllegalArgumentException("Negative values are not supported: " + value); + } + if (value > 0xff_ff_ff_ffL) { + throw new IllegalArgumentException("Value is too high: " + value); + } + wrt.directWrite((int)(value & 0xff)); + wrt.directWrite((int)((value >> 8) & 0xff)); + wrt.directWrite((int)((value >> 16) & 0xff)); + wrt.directWrite((int)((value >> 24) & 0xff)); + } +} diff --git a/src/main/java/com/limechain/rpc/server/CommonConfig.java b/src/main/java/com/limechain/rpc/server/CommonConfig.java index 9f80ccf2e..008197782 100644 --- a/src/main/java/com/limechain/rpc/server/CommonConfig.java +++ b/src/main/java/com/limechain/rpc/server/CommonConfig.java @@ -19,24 +19,18 @@ public class CommonConfig { private static Map, Object> beans = new HashMap<>(); - private static final DivLogger log = new DivLogger(); public static void start() { getBean(SystemInfo.class); getBean(HostConfig.class); getBean(KVRepository.class); - Object bean = getBean(WarpSyncMachine.class); - log.log("WarpSyncMachina is null " + (bean == null)); - log.log("Building SystemInfo"); + getBean(WarpSyncMachine.class); } protected static Object getBean(Class beanClass) { - log.log("Getting bean: " + beanClass.getSimpleName()); if (beans.containsKey(beanClass)) { - log.log("Bean found in map"); return beans.get(beanClass); } else { - log.log("Bean not found in map, building"); switch (beanClass.getSimpleName()) { case "HostConfig": HostConfig hostConfig = hostConfig(); @@ -97,7 +91,6 @@ private static SyncState syncState(KVRepository repository) { } private static SystemInfo systemInfo(HostConfig hostConfig, SyncState syncState) { - log.log("Building SystemInfo method"); return new SystemInfo(hostConfig, syncState); } diff --git a/src/main/java/com/limechain/rpc/server/RpcApp.java b/src/main/java/com/limechain/rpc/server/RpcApp.java index aa99f8caa..fc891150f 100644 --- a/src/main/java/com/limechain/rpc/server/RpcApp.java +++ b/src/main/java/com/limechain/rpc/server/RpcApp.java @@ -1,13 +1,9 @@ package com.limechain.rpc.server; -import com.limechain.utils.DivLogger; public class RpcApp { - private static final DivLogger log = new DivLogger(); - public void start() { - log.log("RpcApp.start() called"); CommonConfig.start(); } diff --git a/src/main/java/com/limechain/storage/DeleteByPrefixResult.java b/src/main/java/com/limechain/storage/DeleteByPrefixResult.java index 7f712c6c2..65281dc66 100644 --- a/src/main/java/com/limechain/storage/DeleteByPrefixResult.java +++ b/src/main/java/com/limechain/storage/DeleteByPrefixResult.java @@ -1,7 +1,7 @@ package com.limechain.storage; import com.limechain.exception.scale.ScaleEncodingException; -import io.emeraldpay.polkaj.scale.ScaleCodecWriter; +import com.limechain.polkaj.writer.ScaleCodecWriter; import java.io.ByteArrayOutputStream; import java.io.IOException; diff --git a/src/main/java/com/limechain/storage/block/SyncState.java b/src/main/java/com/limechain/storage/block/SyncState.java index 3334002b4..5381ef056 100644 --- a/src/main/java/com/limechain/storage/block/SyncState.java +++ b/src/main/java/com/limechain/storage/block/SyncState.java @@ -3,9 +3,12 @@ import com.limechain.chain.lightsyncstate.Authority; import com.limechain.chain.lightsyncstate.LightSyncState; import com.limechain.constants.GenesisBlockHash; +import com.limechain.exception.storage.HeaderNotFoundException; +import com.limechain.network.protocol.grandpa.messages.commit.CommitMessage; +import com.limechain.network.protocol.warp.dto.BlockHeader; +import com.limechain.polkaj.Hash256; import com.limechain.storage.DBConstants; import com.limechain.storage.KVRepository; -import io.emeraldpay.polkaj.types.Hash256; import lombok.Getter; import lombok.Setter; import lombok.extern.java.Log; @@ -32,10 +35,20 @@ public SyncState(KVRepository repository) { if (repository != null) { loadPersistedState(); + } else { + loadDefaultState(); } this.startingBlock = this.lastFinalizedBlockNumber; } + private void loadDefaultState() { + this.lastFinalizedBlockNumber = BigInteger.ZERO; + this.lastFinalizedBlockHash = new Hash256(genesisBlockHash.getBytes()); + this.authoritySet = new Authority[0]; + this.latestRound = BigInteger.ONE; + this.setId = BigInteger.ZERO; + } + private void loadPersistedState() { this.lastFinalizedBlockNumber = (BigInteger) repository.find(DBConstants.LAST_FINALIZED_BLOCK_NUMBER).orElse(BigInteger.ZERO); @@ -54,19 +67,19 @@ public void persistState() { repository.save(DBConstants.SET_ID, setId); } -// public void finalizeHeader(BlockHeader header) { -// this.lastFinalizedBlockNumber = header.getBlockNumber(); -// this.lastFinalizedBlockHash = header.getHash(); -// } + public void finalizeHeader(BlockHeader header) { + this.lastFinalizedBlockNumber = header.getBlockNumber(); + this.lastFinalizedBlockHash = header.getHash(); + } -// public void finalizedCommitMessage(CommitMessage commitMessage) { -// try { -// this.lastFinalizedBlockHash = commitMessage.getVote().getBlockHash(); -// this.lastFinalizedBlockNumber = commitMessage.getVote().getBlockNumber(); -// } catch (HeaderNotFoundException ignored) { -// log.fine("Received commit message for a block that is not in the block store"); -// } -// } + public void finalizedCommitMessage(CommitMessage commitMessage) { + try { + this.lastFinalizedBlockHash = commitMessage.getVote().getBlockHash(); + this.lastFinalizedBlockNumber = commitMessage.getVote().getBlockNumber(); + } catch (HeaderNotFoundException ignored) { + log.fine("Received commit message for a block that is not in the block store"); + } + } public BigInteger incrementSetId() { this.setId = this.setId.add(BigInteger.ONE); diff --git a/src/main/java/com/limechain/sync/warpsync/WarpSyncMachine.java b/src/main/java/com/limechain/sync/warpsync/WarpSyncMachine.java index fc5f251d7..2edeecf22 100644 --- a/src/main/java/com/limechain/sync/warpsync/WarpSyncMachine.java +++ b/src/main/java/com/limechain/sync/warpsync/WarpSyncMachine.java @@ -4,21 +4,23 @@ import com.limechain.chain.lightsyncstate.Authority; import com.limechain.chain.lightsyncstate.LightSyncState; import com.limechain.network.Network; +import com.limechain.network.protocol.warp.dto.WarpSyncFragment; +import com.limechain.polkaj.Hash256; import com.limechain.storage.block.SyncState; import com.limechain.sync.warpsync.action.FinishedAction; import com.limechain.sync.warpsync.action.RequestFragmentsAction; import com.limechain.sync.warpsync.action.WarpSyncAction; -import io.emeraldpay.polkaj.types.Hash256; import lombok.Getter; import lombok.Setter; import lombok.extern.java.Log; -import org.javatuples.Pair; +import com.limechain.tuple.Pair; import java.math.BigInteger; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.PriorityQueue; +import java.util.Queue; import java.util.logging.Level; @Log @@ -28,7 +30,7 @@ public class WarpSyncMachine { private final PriorityQueue> scheduledAuthorityChanges; private final ChainInformation chainInformation; -// private Queue fragmentsQueue; + private Queue fragmentsQueue; private final ChainService chainService; private WarpSyncAction warpSyncAction; private final WarpSyncState warpState; @@ -62,10 +64,10 @@ public boolean isSyncing() { public void start() { if (this.chainService.getChainSpec().getLightSyncState() != null) { LightSyncState initState = LightSyncState.decode(this.chainService.getChainSpec().getLightSyncState()); -// if (this.syncState.getLastFinalizedBlockNumber() -// .compareTo(initState.getFinalizedBlockHeader().getBlockNumber()) < 0) { -// this.syncState.setLightSyncState(initState); -// } + if (this.syncState.getLastFinalizedBlockNumber() + .compareTo(initState.getFinalizedBlockHeader().getBlockNumber()) < 0) { + this.syncState.setLightSyncState(initState); + } } final Hash256 initStateHash = this.syncState.getLastFinalizedBlockHash(); @@ -74,14 +76,14 @@ public void start() { this.networkService.updateCurrentSelectedPeerWithNextBootnode(); this.warpSyncAction = new RequestFragmentsAction(initStateHash); - new Thread(() -> { - while (this.warpSyncAction.getClass() != FinishedAction.class) { - this.handleState(); - this.nextState(); - } - - finishWarpSync(); - }).start(); +// new Thread(() -> { +// while (this.warpSyncAction.getClass() != FinishedAction.class) { +// this.handleState(); +// this.nextState(); +// } +// +// finishWarpSync(); +// }).start(); } public void stop() { @@ -93,7 +95,7 @@ public void stop() { private void finishWarpSync() { this.warpState.setWarpSyncFinished(true); // this.networkService.handshakeBootNodes(); - this.syncState.persistState(); +// this.syncState.persistState(); log.info("Warp sync finished."); this.onFinishCallbacks.forEach(Runnable::run); } diff --git a/src/main/java/com/limechain/sync/warpsync/WarpSyncState.java b/src/main/java/com/limechain/sync/warpsync/WarpSyncState.java index 7c64a1f0d..ff916cf99 100644 --- a/src/main/java/com/limechain/sync/warpsync/WarpSyncState.java +++ b/src/main/java/com/limechain/sync/warpsync/WarpSyncState.java @@ -7,7 +7,7 @@ import lombok.Getter; import lombok.Setter; import lombok.extern.java.Log; -import org.javatuples.Pair; +import com.limechain.tuple.Pair; import java.math.BigInteger; import java.util.Comparator; diff --git a/src/main/java/com/limechain/sync/warpsync/action/RequestFragmentsAction.java b/src/main/java/com/limechain/sync/warpsync/action/RequestFragmentsAction.java index 76e0ef5e2..b5861ad2b 100644 --- a/src/main/java/com/limechain/sync/warpsync/action/RequestFragmentsAction.java +++ b/src/main/java/com/limechain/sync/warpsync/action/RequestFragmentsAction.java @@ -1,9 +1,9 @@ package com.limechain.sync.warpsync.action; +import com.limechain.polkaj.Hash256; import com.limechain.rpc.server.AppBean; import com.limechain.sync.warpsync.WarpSyncMachine; import com.limechain.sync.warpsync.WarpSyncState; -import io.emeraldpay.polkaj.types.Hash256; import lombok.extern.java.Log; import java.util.logging.Level; diff --git a/src/main/java/com/limechain/sync/warpsync/scale/ForcedChangeReader.java b/src/main/java/com/limechain/sync/warpsync/scale/ForcedChangeReader.java index 486642bdd..d5281c293 100644 --- a/src/main/java/com/limechain/sync/warpsync/scale/ForcedChangeReader.java +++ b/src/main/java/com/limechain/sync/warpsync/scale/ForcedChangeReader.java @@ -2,10 +2,10 @@ import com.limechain.chain.lightsyncstate.Authority; import com.limechain.chain.lightsyncstate.scale.AuthorityReader; +import com.limechain.polkaj.reader.ListReader; +import com.limechain.polkaj.reader.ScaleCodecReader; +import com.limechain.polkaj.reader.ScaleReader; import com.limechain.sync.warpsync.dto.AuthoritySetChange; -import io.emeraldpay.polkaj.scale.ScaleCodecReader; -import io.emeraldpay.polkaj.scale.ScaleReader; -import io.emeraldpay.polkaj.scale.reader.ListReader; import java.math.BigInteger; diff --git a/src/main/java/com/limechain/sync/warpsync/scale/ScheduledChangeReader.java b/src/main/java/com/limechain/sync/warpsync/scale/ScheduledChangeReader.java index 906ebc352..ee34af7f8 100644 --- a/src/main/java/com/limechain/sync/warpsync/scale/ScheduledChangeReader.java +++ b/src/main/java/com/limechain/sync/warpsync/scale/ScheduledChangeReader.java @@ -2,10 +2,10 @@ import com.limechain.chain.lightsyncstate.Authority; import com.limechain.chain.lightsyncstate.scale.AuthorityReader; +import com.limechain.polkaj.reader.ListReader; +import com.limechain.polkaj.reader.ScaleCodecReader; +import com.limechain.polkaj.reader.ScaleReader; import com.limechain.sync.warpsync.dto.AuthoritySetChange; -import io.emeraldpay.polkaj.scale.ScaleCodecReader; -import io.emeraldpay.polkaj.scale.ScaleReader; -import io.emeraldpay.polkaj.scale.reader.ListReader; import java.math.BigInteger; diff --git a/src/main/java/com/limechain/tuple/Pair.java b/src/main/java/com/limechain/tuple/Pair.java new file mode 100644 index 000000000..26b214e05 --- /dev/null +++ b/src/main/java/com/limechain/tuple/Pair.java @@ -0,0 +1,165 @@ +package com.limechain.tuple; + + +import java.util.Collection; +import java.util.Iterator; + +public final class Pair { + + private static final long serialVersionUID = 2438099850625502138L; + + private static final int SIZE = 2; + + private final A val0; + private final B val1; + + + public static Pair with(final A value0, final B value1) { + return new Pair(value0, value1); + } + + + /** + *

+ * Create tuple from array. Array has to have exactly two elements. + *

+ * + * @param the array component type + * @param array the array to be converted to a tuple + * @return the tuple + */ + public static Pair fromArray(final X[] array) { + if (array == null) { + throw new IllegalArgumentException("Array cannot be null"); + } + if (array.length != 2) { + throw new IllegalArgumentException( + "Array must have exactly 2 elements in order to create a Pair. Size is " + array.length); + } + return new Pair(array[0], array[1]); + } + + + /** + *

+ * Create tuple from collection. Collection has to have exactly two elements. + *

+ * + * @param the collection component type + * @param collection the collection to be converted to a tuple + * @return the tuple + */ + public static Pair fromCollection(final Collection collection) { + return fromIterable(collection); + } + + + /** + *

+ * Create tuple from iterable. Iterable has to have exactly two elements. + *

+ * + * @param the iterable component type + * @param iterable the iterable to be converted to a tuple + * @return the tuple + */ + public static Pair fromIterable(final Iterable iterable) { + return fromIterable(iterable, 0, true); + } + + + /** + *

+ * Create tuple from iterable, starting from the specified index. Iterable + * can have more (or less) elements than the tuple to be created. + *

+ * + * @param the iterable component type + * @param iterable the iterable to be converted to a tuple + * @return the tuple + */ + public static Pair fromIterable(final Iterable iterable, int index) { + return fromIterable(iterable, index, false); + } + + + private static Pair fromIterable(final Iterable iterable, int index, final boolean exactSize) { + + if (iterable == null) { + throw new IllegalArgumentException("Iterable cannot be null"); + } + + boolean tooFewElements = false; + + X element0 = null; + X element1 = null; + + final Iterator iter = iterable.iterator(); + + int i = 0; + while (i < index) { + if (iter.hasNext()) { + iter.next(); + } else { + tooFewElements = true; + } + i++; + } + + if (iter.hasNext()) { + element0 = iter.next(); + } else { + tooFewElements = true; + } + + if (iter.hasNext()) { + element1 = iter.next(); + } else { + tooFewElements = true; + } + + if (tooFewElements && exactSize) { + throw new IllegalArgumentException("Not enough elements for creating a Pair (2 needed)"); + } + + if (iter.hasNext() && exactSize) { + throw new IllegalArgumentException( + "Iterable must have exactly 2 available elements in order to create a Pair."); + } + + return new Pair(element0, element1); + + } + + public Pair(final A value0, + final B value1) { + this.val0 = value0; + this.val1 = value1; + } + + + public A getValue0() { + return this.val0; + } + + + public B getValue1() { + return this.val1; + } + + public int getSize() { + return SIZE; + } + + + public Pair setAt0(final X value) { + return new Pair( + value, this.val1); + } + + public Pair setAt1(final X value) { + return new Pair( + this.val0, value); + } + +} \ No newline at end of file diff --git a/src/main/java/com/limechain/utils/StringUtils.java b/src/main/java/com/limechain/utils/StringUtils.java index 14022ca96..ba21a1768 100644 --- a/src/main/java/com/limechain/utils/StringUtils.java +++ b/src/main/java/com/limechain/utils/StringUtils.java @@ -1,13 +1,12 @@ package com.limechain.utils; import lombok.experimental.UtilityClass; +import org.teavm.jso.JSBody; -import java.security.InvalidParameterException; import java.util.regex.Pattern; @UtilityClass public class StringUtils { - private static final Pattern HEX_PATTERN = Pattern.compile("^(0x)?[0-9a-fA-F]+$"); public static final String HEX_PREFIX = "0x"; /** @@ -17,24 +16,25 @@ public class StringUtils { * * @param hex the hexadecimal string to convert * @return the corresponding byte array - * @throws InvalidParameterException if the hex string has an odd length or does not match the hex pattern + * @throws IllegalArgumentException if the hex string has an odd length or does not match the hex pattern */ public static byte[] hexToBytes(String hex) { if (hex.length() % 2 != 0) { - throw new InvalidParameterException("Invalid hex string length"); - } - - if (!HEX_PATTERN.matcher(hex).matches()) { - throw new InvalidParameterException("Invalid hex string"); + throw new IllegalArgumentException("Invalid hex string length"); } // Trim the 0x prefix if it exists hex = remove0xPrefix(hex); -// return ByteString.fromHex(hex).toByteArray(); - return null; + return fromHex(hex); } + @JSBody(params = { "hex" }, script = " let bytes = [];" + + " for (let c = 0; c < hex.length; c += 2)" + + " bytes.push(parseInt(hex.substr(c, 2), 16));" + + " return bytes;") + public static native byte[] fromHex(String hex); + /** * Removes the "0x" prefix from a hexadecimal string, if it exists. * This is useful for cleaning up hex strings to ensure they can be processed or parsed elsewhere. diff --git a/src/main/java/com/limechain/utils/scale/ScaleUtils.java b/src/main/java/com/limechain/utils/scale/ScaleUtils.java index c8fa5f8d3..5c4fcd7ce 100644 --- a/src/main/java/com/limechain/utils/scale/ScaleUtils.java +++ b/src/main/java/com/limechain/utils/scale/ScaleUtils.java @@ -1,8 +1,8 @@ package com.limechain.utils.scale; import com.limechain.exception.scale.ScaleEncodingException; -import io.emeraldpay.polkaj.scale.ScaleCodecWriter; -import io.emeraldpay.polkaj.scale.ScaleWriter; +import com.limechain.polkaj.writer.ScaleCodecWriter; +import com.limechain.polkaj.writer.ScaleWriter; import lombok.experimental.UtilityClass; import java.io.ByteArrayOutputStream; diff --git a/src/main/webapp/index.html b/src/main/webapp/index.html index c3f2088e9..a94bf6767 100644 --- a/src/main/webapp/index.html +++ b/src/main/webapp/index.html @@ -1,7 +1,7 @@ - TeaVM example + Fruzhin @@ -19,9 +19,17 @@ - + \ No newline at end of file diff --git a/src/test/resources/application.properties b/src/test/resources/application.properties deleted file mode 100644 index c65e8cb01..000000000 --- a/src/test/resources/application.properties +++ /dev/null @@ -1,10 +0,0 @@ -host.name=Fruzhin -host.version=0.3.0 -# Genesis json data -genesis.path.polkadot=genesis/polkadot.json -genesis.path.kusama=genesis/ksmcc3.json -genesis.path.westend=genesis/westend2.json -genesis.path.local=genesis/westend-local.json - -#logging.level.root=DEBUG -logging.level.com.limechain.runtime.hostapi=DEBUG \ No newline at end of file diff --git a/src/test/resources/runtime.data b/src/test/resources/runtime.data deleted file mode 100644 index e08efd9ee..000000000 Binary files a/src/test/resources/runtime.data and /dev/null differ diff --git a/src/test/resources/runtime.wasm b/src/test/resources/runtime.wasm deleted file mode 100644 index 9c33a4bde..000000000 Binary files a/src/test/resources/runtime.wasm and /dev/null differ diff --git a/src/test/resources/runtime_sections.wasm b/src/test/resources/runtime_sections.wasm deleted file mode 100644 index 7a47da37d..000000000 Binary files a/src/test/resources/runtime_sections.wasm and /dev/null differ diff --git a/src/test/resources/runtime_sections_memory_export.wasm b/src/test/resources/runtime_sections_memory_export.wasm deleted file mode 100644 index f4939db91..000000000 Binary files a/src/test/resources/runtime_sections_memory_export.wasm and /dev/null differ diff --git a/src/test/resources/runtime_sections_without_memory.wasm b/src/test/resources/runtime_sections_without_memory.wasm deleted file mode 100644 index 7be1bc526..000000000 Binary files a/src/test/resources/runtime_sections_without_memory.wasm and /dev/null differ diff --git a/src/test/resources/short_polkadot.json b/src/test/resources/short_polkadot.json deleted file mode 100644 index e1f764bc0..000000000 --- a/src/test/resources/short_polkadot.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "name": "Polkadot", - "id": "polkadot", - "chainType": "Live", - "bootNodes": [ - "/dns/polkadot-connect-0.parity.io/tcp/443/wss/p2p/12D3KooWEPmjoRpDSUuiTjvyNDd8fejZ9eNWH5bE965nyBMDrB4o", - "/dns/cc1-1.parity.tech/tcp/30333/p2p/12D3KooWFN2mhgpkJsDBuNuE5427AcDrsib8EoqGMZmkxWwx3Md4" - ], - "telemetryEndpoints": [ - [ - "wss://telemetry.polkadot.io/submit/", - 0 - ] - ], - "protocolId": "dot", - "properties": { - "ss58Format": 0, - "tokenDecimals": 10, - "tokenSymbol": "DOT" - }, - "forkBlocks": null, - "badBlocks": null, - "consensusEngine": null, - "genesis": { - "top": { - "0x9c5d795d0297be56027a4b2464e3339763e6d3c1fb15805edfd024172ea4817d9e40ca7bd1fd588ca534ee6b96a65ca8a53ec232dda838cc3cd2bd1887904906": "0x11bc2c7ea454e083cea1186239abc83733200e78", - "0x9c5d795d0297be56027a4b2464e333979c5d795d0297be56027a4b2464e33397eb0718ce75762eeba4570943d5b2de2afb9085b6": "0x000e760ff72301000000000000000000" - }, - "childrenDefault": {} - }, - "lightSyncState": { - "babeEpochChanges": "0x045b5ad8c1dcec0b19d70f5255bd200", - "babeFinalizedBlockWeight": 2880292, - "finalizedBlockHeader": "0x486e93538fbbaf1982", - "grandpaAuthoritySet": "0xa50497es005ff7af00" - } -} \ No newline at end of file diff --git a/wasmer-setup/linux/amd/libwasmer_jni.so b/wasmer-setup/linux/amd/libwasmer_jni.so deleted file mode 100755 index 1a3aff7e1..000000000 Binary files a/wasmer-setup/linux/amd/libwasmer_jni.so and /dev/null differ diff --git a/wasmer-setup/linux/arm/libwasmer_jni.so b/wasmer-setup/linux/arm/libwasmer_jni.so deleted file mode 100755 index 0f0ed200b..000000000 Binary files a/wasmer-setup/linux/arm/libwasmer_jni.so and /dev/null differ diff --git a/wasmer-setup/linux/i686/libwasmer_jni.so b/wasmer-setup/linux/i686/libwasmer_jni.so deleted file mode 100755 index 29287894b..000000000 Binary files a/wasmer-setup/linux/i686/libwasmer_jni.so and /dev/null differ diff --git a/wasmer-setup/mac/amd/libwasmer_jni.dylib b/wasmer-setup/mac/amd/libwasmer_jni.dylib deleted file mode 100644 index d82ab30c8..000000000 Binary files a/wasmer-setup/mac/amd/libwasmer_jni.dylib and /dev/null differ diff --git a/wasmer-setup/mac/arm/libwasmer_jni.dylib b/wasmer-setup/mac/arm/libwasmer_jni.dylib deleted file mode 100755 index 1e3a39fbb..000000000 Binary files a/wasmer-setup/mac/arm/libwasmer_jni.dylib and /dev/null differ diff --git a/wasmer-setup/windows/amd/wasmer_jni.dll b/wasmer-setup/windows/amd/wasmer_jni.dll deleted file mode 100755 index 07c21e155..000000000 Binary files a/wasmer-setup/windows/amd/wasmer_jni.dll and /dev/null differ