Compare commits

..

21 Commits

Author SHA1 Message Date
147542f10c
correct median; on genesis validators list is empty
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-11-28 00:02:26 +03:00
d45cc9bd13
add latest from_block to logs
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-11-27 19:22:48 +03:00
7c57b9ea3f
update chain specs for local testing
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-11-27 19:08:43 +03:00
638d31ba28
update casper runtime based on ghost pallets
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-11-27 19:07:59 +03:00
c9b4325c04
rustfmt slow-clap pallet
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-11-27 19:06:18 +03:00
911db3b974
apply changes from ghost-traits for ExposureListener
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-11-27 19:04:24 +03:00
fbc58e350b
conversion function to AccountId added
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-11-27 19:03:13 +03:00
b692959369
rustfmt ghost slow clap pallet
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-11-27 17:16:07 +03:00
16b933f3ba
rustfmt ghost traits pallet
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-11-27 17:15:30 +03:00
ad3de30be3
rustfmt ghost networks pallet
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-11-27 17:15:03 +03:00
e3c8e51749
update casper runtime in accordance with new functionality. not final
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-11-27 17:12:22 +03:00
d3c5380ba7
updated version of slow clap
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-11-27 17:10:57 +03:00
c3ef933c20
extend networks pallet with avg_block_speed
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-11-27 17:10:23 +03:00
954ae66294
bump traits package version
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-11-27 17:09:10 +03:00
a504d8eb87
trait to get exposure from external pallets such as staking
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-11-27 17:08:16 +03:00
eebcc18018
simple bitmap implementation
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-11-27 17:06:50 +03:00
3be36b6db2
set ghost emoji as prefix for logging
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-11-21 13:49:40 +03:00
6a2b5a34d2
applause based on the external expousre
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-11-21 13:46:22 +03:00
0bb46482b2
offchain worker restructure and block commitments added
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-11-20 03:06:48 +03:00
d76646c191
remove unused structs to avoid warning during compilation
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-11-18 16:01:29 +03:00
94d28f254f
update offchain worker logic
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-11-18 16:00:17 +03:00
29 changed files with 2380 additions and 1905 deletions

10
Cargo.lock generated
View File

@ -1186,7 +1186,7 @@ dependencies = [
[[package]]
name = "casper-runtime"
version = "3.5.36"
version = "3.5.34"
dependencies = [
"casper-runtime-constants",
"frame-benchmarking",
@ -1204,6 +1204,7 @@ dependencies = [
"ghost-runtime-common",
"ghost-slow-clap",
"ghost-sudo",
"ghost-traits",
"log",
"pallet-alliance",
"pallet-authority-discovery",
@ -3649,7 +3650,7 @@ dependencies = [
[[package]]
name = "ghost-networks"
version = "0.1.16"
version = "0.1.19"
dependencies = [
"frame-benchmarking",
"frame-support",
@ -3836,12 +3837,13 @@ dependencies = [
[[package]]
name = "ghost-slow-clap"
version = "0.3.53"
version = "0.4.1"
dependencies = [
"frame-benchmarking",
"frame-support",
"frame-system",
"ghost-networks",
"ghost-traits",
"log",
"pallet-balances",
"pallet-session",
@ -3887,7 +3889,7 @@ dependencies = [
[[package]]
name = "ghost-traits"
version = "0.3.23"
version = "0.3.25"
dependencies = [
"frame-support",
"sp-runtime 31.0.1",

View File

@ -17,7 +17,7 @@ homepage.workspace = true
[workspace.package]
license = "GPL-3.0-only"
authors = ["571nky", "57r37ch", "f4750"]
version = "0.8.2"
version = "0.8.3"
edition = "2021"
homepage = "https://ghostchain.io"
repository = "https://git.ghostchain.io/ghostchain/ghost-node"

126
README.md
View File

@ -150,8 +150,28 @@ rustup default stable
rustup update
```
Add the nightly release and the nightly WebAssembly (wasm) targets
to your development environment by running the following commands:
```bash
rustup target add wasm32-unknown-unknown --toolchain stable
rustup update nightly
```
```bash
rustup target add wasm32-unknown-unknown --toolchain nightly
```
```bash
rustup target add wasm32-unknown-unknown --toolchain stable-x86_64-unknown-linux-gnu
```
If you are trying to install WebAssembly (wasm) on an ARM-based processor like the ones in Raspberry Pi try this instead:
```bash
rustup target add wasm32-unknown-unknown --toolchain stable-aarch64-unknown-linux-gnu
```
**_IF error try_**
```bash
rustup target add wasm32-unknown-unknown --toolchain default
```
Verify the configuration of your development environment by running
@ -160,6 +180,10 @@ the following command:
rustup show
```
```bash
rustup +nightly show
```
You should see something like this:
![images/img_9.png](images/img_9.png)
@ -170,6 +194,13 @@ Now run:
rustup component add rust-src --toolchain stable
```
**_IF error try_**
```bash
rustup component add rust-src --toolchain default
```
## Install GHOST
Check if Git is already installed:
@ -180,7 +211,7 @@ git --version
Make a GHOST Directory and go to it:
```bash
mkdir ~/ghost && cd ~/ghost
mkdir ghost && cd ghost
```
Clone GHOST Node Git:
@ -195,7 +226,7 @@ cd ghost-node
Compile the node template by running the following command:
```bash
./scripts/starter.sh --release
cargo build --release
```
The build can take up to 20 minutes depending on the specifications of your machine.
@ -203,6 +234,7 @@ The build can take up to 20 minutes depending on the specifications of your mach
![images/img_12.png](images/img_12.png)
# Boot Node Qualification
## Boot Node Qualification Test
@ -288,7 +320,7 @@ Only `port 30333` should be opened.
Press _CTRL+C_ to stop the node.
# Launching GHOST TestNet
# Launching GHOST TestNet 3.1
Switch to main GIT branch:
```bash
@ -316,7 +348,66 @@ To generate the node key use the following command:
./target/release/ghost key generate-node-key --bin --file=/etc/ghost/node-key
```
Feel free to backup the file on a separate storage device.
Generate Wallet Key file with the following command:
```bash
./target/release/ghost key generate | grep "Secret seed" | awk '{$1=$2=""; sub(/^[ \t]+/, ""); print}' > /etc/ghost/wallet-key
```
Display the wallet-key on the screen by using cat command:
```bash
./target/release/ghost key inspect $(cat /etc/ghost/wallet-key)
```
![images/img_22.png](images/img_22.png)
Feel free to back the file on a separate storage device.
Generate Stash Key file with the following command:
```bash
./target/release/ghost key generate | grep "Secret seed" | awk '{$1=$2=""; sub(/^[ \t]+/, ""); print}' > /etc/ghost/stash-key
```
Display the stash-key on the screen by using cat command:
```bash
./target/release/ghost key inspect $(cat /etc/ghost/stash-key)
```
![images/img_23.png](images/img_23.png)
Generate Session Key file with the following command:
```bash
./target/release/ghost key generate | grep "Secret seed" | awk '{$1=$2=""; sub(/^[ \t]+/, ""); print}' > /etc/ghost/session-key
```
You have generates 4 types of Session Keys:
1. Session Key AUDI
2. Session Key BABE
3. Session Key SLOW
4. Session Key GRAN
Now let's display them!
Display the session-key//audi on the screen by using cat command:
```bash
./target/release/ghost key inspect "$(cat /etc/ghost/session-key)//audi"
```
![images/img_24.png](images/img_24.png)
Display the session-key//babe on the screen by using cat command:
```bash
./target/release/ghost key inspect "$(cat /etc/ghost/session-key)//babe"
```
![images/img_25.png](images/img_25.png)
Display the session-key//slow on the screen by using cat command:
```bash
./target/release/ghost key inspect "$(cat /etc/ghost/session-key)//slow"
```
![images/img_26.png](images/img_26.png)
Display the session-key//gran on the screen by using cat command:
```bash
./target/release/ghost key inspect "$(cat /etc/ghost/session-key)//gran" --scheme=ed25519
```
![images/img_27.png](images/img_27.png)
## Build and start the ghost-node
@ -346,7 +437,7 @@ sha256sum /etc/ghost/casper.json
You should see:
```
9da6045ed6d4fd844e3939573b31c013d0e564e542029330faa6d978cb4a915a
ad653233c978bfd00c5e4525b17628632bc4319c5f5f4b4dcc2f050ef3c3d145
```
Create running `ghost-node` service that starts on system boot using `--unit-file` flag.
@ -372,7 +463,10 @@ To choose default options press Enter here:
![images/img_30.png](images/img_30.png)
If you want to validate from this node press Enter:
Currently, you have to qualify to become a validator node through [GHOST Whales](https://ghostchain.io/whales-apply).
If you were NOT included in the [ghosties file](https://git.ghostchain.io/ghostchain/ghost-node/src/branch/main/service/ghosties) then you cannot be a validator node,
and you can only be a full node so for `disable validator mode? [y/N]` type `y`.
If you were included in the ghosties file you can press Enter:
```
disable validator mode? [y/N]: y
```
@ -417,6 +511,17 @@ Type `y` and press _Enter_ for create dedicated user for running `ghost-node`:
![images/img_37.png](images/img_37.png)
Now you can check whether or not the keys on your GHOST Node match those
in the [ghosties file](https://git.ghostchain.io/ghostchain/ghost-node/src/branch/main/service/ghosties) on GHOST Git.
If you are running a **Validator Node** and if you have followed
the Generating Keys Part you will see all `[+]`.
If you are a running a **Full Node** you will see errors:
(Press _Enter_ for prompts)
```bash
./scripts/starter.sh --check-keys
```
Full Node:
![images/img_38.png](images/img_38.png)
@ -430,7 +535,7 @@ Start `ghost-node`:
sudo systemctl start ghost-node
```
Wait ~60 seconds!
Wait 60 seconds!
Check node is started:
```bash
@ -440,6 +545,11 @@ sudo systemctl status ghost-node
For exit press _CTRL+C_
In order to insert keys run the following flags `--check-keys` `--insert-keys`:
```bash
./scripts/starter.sh --check-keys --insert-keys
```
Restart `ghost-node`:
```bash
sudo systemctl restart ghost-node

View File

@ -51,33 +51,6 @@ pub trait WeightInfo {
fn claim() -> Weight;
}
/// Weight for ghost_claims using the Substrate node and recommended hardware.
pub struct SubstrateWeight<T>(PhantomData<T>);
impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
/// Storage: `System::Account` (r:2 w:2)
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
/// Storage: `GhostClaims::Total` (r:1 w:1)
/// Proof: `GhostClaims::Total` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `CultCollective::Members` (r:2 w:2)
/// Proof: `CultCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`)
/// Storage: `CultCollective::MemberCount` (r:6 w:6)
/// Proof: `CultCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`)
/// Storage: `CultCollective::IdToIndex` (r:6 w:12)
/// Proof: `CultCollective::IdToIndex` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`)
/// Storage: `CultCollective::IndexToId` (r:0 w:6)
/// Proof: `CultCollective::IndexToId` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`)
fn claim() -> Weight {
// Proof Size summary in bytes:
// Measured: `896`
// Estimated: `16164`
// Minimum execution time: 754_086_000 picoseconds.
Weight::from_parts(756_147_000, 0)
.saturating_add(Weight::from_parts(0, 16164))
.saturating_add(T::DbWeight::get().reads(17))
.saturating_add(T::DbWeight::get().writes(29))
}
}
impl WeightInfo for () {
/// Storage: `System::Account` (r:2 w:2)
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)

View File

@ -1,6 +1,6 @@
[package]
name = "ghost-networks"
version = "0.1.16"
version = "0.1.19"
license.workspace = true
authors.workspace = true
edition.workspace = true

View File

@ -43,6 +43,7 @@ fn prepare_network<T: Config>(
gatekeeper,
topic_name,
network_type: NetworkType::Evm,
avg_block_speed: 12,
finality_delay: 69,
rate_limit_delay: 69,
block_distance: 69,
@ -239,6 +240,20 @@ benchmarks! {
assert_ne!(GhostNetworks::<T>::networks(chain_id.clone()), prev_network);
}
update_avg_block_speed {
let avg_block_speed = 420;
let (chain_id, network) = prepare_network::<T>(1, 1, 1);
let authority = T::UpdateOrigin::try_successful_origin()
.map_err(|_| BenchmarkError::Weightless)?;
let prev_network = create_network::<T>(chain_id.clone(), network.clone())?;
}: _<T::RuntimeOrigin>(authority, chain_id.clone(), avg_block_speed)
verify {
assert_last_event::<T>(Event::NetworkAvgBlockSpeedUpdated {
chain_id: chain_id.clone(), avg_block_speed,
}.into());
assert_ne!(GhostNetworks::<T>::networks(chain_id.clone()), prev_network);
}
remove_network {
let (chain_id, network) = prepare_network::<T>(1, 1, 1);
let authority = T::RemoveOrigin::try_successful_origin()

View File

@ -38,7 +38,7 @@ mod tests;
pub type BalanceOf<T> =
<<T as Config>::Currency as Inspect<<T as frame_system::Config>::AccountId>>::Balance;
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub enum NetworkType {
Evm = 0,
Utxo = 1,
@ -61,6 +61,7 @@ pub struct NetworkData {
pub finality_delay: u64,
pub rate_limit_delay: u64,
pub block_distance: u64,
pub avg_block_speed: u64,
pub incoming_fee: u32,
pub outgoing_fee: u32,
}
@ -220,6 +221,10 @@ pub mod module {
chain_id: T::NetworkId,
outgoing_fee: u32,
},
NetworkAvgBlockSpeedUpdated {
chain_id: T::NetworkId,
avg_block_speed: u64,
},
NetworkRemoved {
chain_id: T::NetworkId,
},
@ -433,6 +438,17 @@ pub mod module {
}
#[pallet::call_index(11)]
#[pallet::weight(T::WeightInfo::update_avg_block_speed())]
pub fn update_avg_block_speed(
origin: OriginFor<T>,
chain_id: T::NetworkId,
avg_block_speed: u64,
) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_avg_block_speed(chain_id, avg_block_speed)
}
#[pallet::call_index(12)]
#[pallet::weight(T::WeightInfo::remove_network())]
pub fn remove_network(origin: OriginFor<T>, chain_id: T::NetworkId) -> DispatchResult {
T::RemoveOrigin::ensure_origin_or_root(origin)?;
@ -589,7 +605,7 @@ impl<T: Config> Pallet<T> {
Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult {
ensure!(maybe_network.is_some(), Error::<T>::NetworkDoesNotExist);
let net = maybe_network.as_mut().unwrap();
net.network_type = network_type.clone();
net.network_type = network_type;
*maybe_network = Some(net.clone());
Ok(())
})?;
@ -653,7 +669,7 @@ impl<T: Config> Pallet<T> {
Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult {
ensure!(maybe_network.is_some(), Error::<T>::NetworkDoesNotExist);
let net = maybe_network.as_mut().unwrap();
net.incoming_fee = incoming_fee.clone();
net.incoming_fee = incoming_fee;
*maybe_network = Some(net.clone());
Ok(())
})?;
@ -671,7 +687,7 @@ impl<T: Config> Pallet<T> {
Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult {
ensure!(maybe_network.is_some(), Error::<T>::NetworkDoesNotExist);
let net = maybe_network.as_mut().unwrap();
net.outgoing_fee = outgoing_fee.clone();
net.outgoing_fee = outgoing_fee;
*maybe_network = Some(net.clone());
Ok(())
})?;
@ -681,6 +697,24 @@ impl<T: Config> Pallet<T> {
});
Ok(())
}
pub fn do_update_avg_block_speed(
chain_id: T::NetworkId,
avg_block_speed: u64,
) -> DispatchResult {
Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult {
ensure!(maybe_network.is_some(), Error::<T>::NetworkDoesNotExist);
let net = maybe_network.as_mut().unwrap();
net.avg_block_speed = avg_block_speed;
*maybe_network = Some(net.clone());
Ok(())
})?;
Self::deposit_event(Event::<T>::NetworkAvgBlockSpeedUpdated {
chain_id,
avg_block_speed,
});
Ok(())
}
}
impl<T: Config> NetworkDataBasicHandler for Pallet<T> {

View File

@ -13,7 +13,6 @@ where
+ sp_std::ops::Shr<Output = Balance>
+ sp_std::ops::BitAnd<Balance, Output = Balance>,
{
fn zero(&self) -> Balance {
0u32.into()
}

View File

@ -98,7 +98,7 @@ impl ghost_networks::Config for Test {
type RegisterOrigin = EnsureSignedBy<RegistererAccount, AccountId>;
type UpdateOrigin = EnsureSignedBy<UpdaterAccount, AccountId>;
type RemoveOrigin = EnsureSignedBy<RemoverAccount, AccountId>;
type WeightInfo = crate::weights::SubstrateWeight<Test>;
type WeightInfo = ();
}
type Block = frame_system::mocking::MockBlock<Test>;

View File

@ -19,6 +19,7 @@ fn prepare_network_data() -> (u32, NetworkData) {
finality_delay: 69,
rate_limit_delay: 69,
block_distance: 69,
avg_block_speed: 12_000,
network_type: NetworkType::Evm,
gatekeeper: b"0x1234567891234567891234567891234567891234".to_vec(),
topic_name: b"0x12345678912345678912345678912345678912345678912345678912345678"
@ -1882,7 +1883,7 @@ fn check_bridged_inflation_curve_for_big_commissions() {
let (payout, rest) = BridgedInflationCurve::<RewardCurve, Test>::era_payout(
total_staked_gt_ideal,
total_issuance + amount,
0
0,
);
assert!(payout < commission);
assert!(rest < commission);
@ -1890,7 +1891,7 @@ fn check_bridged_inflation_curve_for_big_commissions() {
let (payout, rest) = BridgedInflationCurve::<RewardCurve, Test>::era_payout(
total_staked_lt_ideal,
total_issuance + amount,
0
0,
);
assert!(payout < commission);
assert!(rest < commission);

View File

@ -60,169 +60,10 @@ pub trait WeightInfo {
fn update_network_topic_name() -> Weight;
fn update_incoming_network_fee() -> Weight;
fn update_outgoing_network_fee() -> Weight;
fn update_avg_block_speed() -> Weight;
fn remove_network() -> Weight;
}
/// Weight for ghost_networks using the Substrate node and recommended hardware.
pub struct SubstrateWeight<T>(PhantomData<T>);
impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// The range of component `i` is `[1, 20]`.
/// The range of component `j` is `[1, 150]`.
/// The range of component `k` is `[1, 20]`.
fn register_network(_i: u32, _j: u32, k: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `109`
// Estimated: `3574`
// Minimum execution time: 46_023_000 picoseconds.
Weight::from_parts(97_871_287, 0)
.saturating_add(Weight::from_parts(0, 3574))
// Standard Error: 94_524
.saturating_add(Weight::from_parts(940_486, 0).saturating_mul(k.into()))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// The range of component `n` is `[1, 20]`.
fn update_network_name(n: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `302`
// Estimated: `3767`
// Minimum execution time: 49_906_000 picoseconds.
Weight::from_parts(55_537_587, 0)
.saturating_add(Weight::from_parts(0, 3767))
// Standard Error: 87_704
.saturating_add(Weight::from_parts(92_366, 0).saturating_mul(n.into()))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// The range of component `n` is `[1, 150]`.
fn update_network_endpoint(n: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `302`
// Estimated: `3767`
// Minimum execution time: 50_556_000 picoseconds.
Weight::from_parts(57_726_674, 0)
.saturating_add(Weight::from_parts(0, 3767))
// Standard Error: 12_261
.saturating_add(Weight::from_parts(274, 0).saturating_mul(n.into()))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_finality_delay() -> Weight {
// Proof Size summary in bytes:
// Measured: `302`
// Estimated: `3767`
// Minimum execution time: 49_406_000 picoseconds.
Weight::from_parts(51_256_000, 0)
.saturating_add(Weight::from_parts(0, 3767))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_rate_limit_delay() -> Weight {
// Proof Size summary in bytes:
// Measured: `302`
// Estimated: `3767`
// Minimum execution time: 49_572_000 picoseconds.
Weight::from_parts(52_584_000, 0)
.saturating_add(Weight::from_parts(0, 3767))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_block_distance() -> Weight {
// Proof Size summary in bytes:
// Measured: `302`
// Estimated: `3767`
// Minimum execution time: 48_880_000 picoseconds.
Weight::from_parts(50_596_000, 0)
.saturating_add(Weight::from_parts(0, 3767))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_type() -> Weight {
// Proof Size summary in bytes:
// Measured: `302`
// Estimated: `3767`
// Minimum execution time: 48_282_000 picoseconds.
Weight::from_parts(49_137_000, 0)
.saturating_add(Weight::from_parts(0, 3767))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_gatekeeper() -> Weight {
// Proof Size summary in bytes:
// Measured: `302`
// Estimated: `3767`
// Minimum execution time: 50_853_000 picoseconds.
Weight::from_parts(51_982_000, 0)
.saturating_add(Weight::from_parts(0, 3767))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_topic_name() -> Weight {
// Proof Size summary in bytes:
// Measured: `302`
// Estimated: `3767`
// Minimum execution time: 50_343_000 picoseconds.
Weight::from_parts(52_380_000, 0)
.saturating_add(Weight::from_parts(0, 3767))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_incoming_network_fee() -> Weight {
// Proof Size summary in bytes:
// Measured: `302`
// Estimated: `3767`
// Minimum execution time: 49_393_000 picoseconds.
Weight::from_parts(80_966_000, 0)
.saturating_add(Weight::from_parts(0, 3767))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_outgoing_network_fee() -> Weight {
// Proof Size summary in bytes:
// Measured: `302`
// Estimated: `3767`
// Minimum execution time: 49_579_000 picoseconds.
Weight::from_parts(51_126_000, 0)
.saturating_add(Weight::from_parts(0, 3767))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn remove_network() -> Weight {
// Proof Size summary in bytes:
// Measured: `302`
// Estimated: `3767`
// Minimum execution time: 44_634_000 picoseconds.
Weight::from_parts(45_815_000, 0)
.saturating_add(Weight::from_parts(0, 3767))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
}
impl WeightInfo for () {
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
@ -369,6 +210,18 @@ impl WeightInfo for () {
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_avg_block_speed() -> Weight {
// Proof Size summary in bytes:
// Measured: `302`
// Estimated: `3767`
// Minimum execution time: 49_579_000 picoseconds.
Weight::from_parts(51_126_000, 0)
.saturating_add(Weight::from_parts(0, 3767))
.saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1))
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn remove_network() -> Weight {
// Proof Size summary in bytes:
// Measured: `302`

View File

@ -1,6 +1,6 @@
[package]
name = "ghost-slow-clap"
version = "0.3.53"
version = "0.4.5"
description = "Applause protocol for the EVM bridge"
license.workspace = true
authors.workspace = true
@ -28,6 +28,7 @@ sp-io = { workspace = true }
sp-std = { workspace = true }
ghost-networks = { workspace = true }
ghost-traits = { workspace = true }
[dev-dependencies]
pallet-balances = { workspace = true }

View File

@ -3,7 +3,6 @@
use super::*;
use frame_benchmarking::v1::*;
use frame_support::traits::fungible::Inspect;
use frame_system::RawOrigin;
pub fn create_account<T: Config>() -> T::AccountId {
@ -12,73 +11,45 @@ pub fn create_account<T: Config>() -> T::AccountId {
.expect("32 bytes always construct an AccountId32")
}
pub fn prepare_evm_network<T: Config>(network_id: NetworkIdOf<T>) {
let network_data = NetworkData {
chain_name: "Ethereum".into(),
default_endpoints: vec![b"https://other.endpoint.network.com".to_vec()],
finality_delay: 69,
avg_block_speed: 69,
rate_limit_delay: 69,
block_distance: 69,
network_type: ghost_networks::NetworkType::Evm,
gatekeeper: b"0x4d224452801ACEd8B2F0aebE155379bb5D594381".to_vec(),
topic_name: b"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef".to_vec(),
incoming_fee: 0,
outgoing_fee: 0,
};
let _ = T::NetworkDataHandler::register(network_id, network_data.clone());
}
benchmarks! {
slow_clap {
let network_id = NetworkIdOf::<T>::default();
prepare_evm_network::<T>(network_id);
let minimum_balance = <<T as pallet::Config>::Currency>::minimum_balance();
let receiver = create_account::<T>();
let amount = minimum_balance + minimum_balance;
let network_id = NetworkIdOf::<T>::default();
let session_index = T::ValidatorSet::session_index();
let transaction_hash = H256::repeat_byte(1u8);
let authorities = vec![T::AuthorityId::generate_pair(None)];
let bounded_authorities = WeakBoundedVec::<_, T::MaxAuthorities>::try_from(authorities.clone())
.map_err(|()| "more than the maximum number of keys provided")?;
Authorities::<T>::set(&session_index, bounded_authorities);
let authority_index = 0u32;
let clap = Clap {
session_index: 0,
authority_index: 0,
transaction_hash: H256::repeat_byte(1u8),
block_number: 69,
removed: false,
network_id,
receiver: receiver.clone(),
amount,
};
let authority_id = authorities
.get(0usize)
.expect("first authority should exist");
let encoded_clap = clap.encode();
let signature = authority_id.sign(&encoded_clap)
.ok_or("couldn't make signature")?;
}: _(RawOrigin::None, clap, signature)
verify {
assert_eq!(<<T as pallet::Config>::Currency>::total_balance(&receiver), amount);
}
self_applause {
let session_index = T::ValidatorSet::session_index();
let next_session_index = session_index.saturating_add(1);
let authorities = vec![
T::AuthorityId::generate_pair(None),
T::AuthorityId::generate_pair(None),
];
let bounded_authorities = WeakBoundedVec::<_, T::MaxAuthorities>::try_from(authorities.clone())
.map_err(|()| "more than the maximum number of keys provided")?;
Authorities::<T>::set(&session_index, bounded_authorities.clone());
Authorities::<T>::set(&next_session_index, bounded_authorities);
let minimum_balance = <<T as pallet::Config>::Currency>::minimum_balance();
let receiver = create_account::<T>();
let receiver_clone = receiver.clone();
let amount = minimum_balance + minimum_balance;
let network_id = NetworkIdOf::<T>::default();
let transaction_hash = H256::repeat_byte(1u8);
let unique_transaction_hash = <Pallet<T>>::generate_unique_hash(
&receiver,
&amount,
&network_id,
);
let storage_key = (session_index, &transaction_hash, &unique_transaction_hash);
let next_storage_key = (next_session_index, &transaction_hash, &unique_transaction_hash);
<Pallet::<T>>::trigger_nullification_for_benchmark();
let clap = Clap {
session_index,
authority_index: 0,
authority_index,
transaction_hash,
block_number: 69,
removed: false,
@ -86,28 +57,61 @@ benchmarks! {
receiver: receiver.clone(),
amount,
};
let args_hash = Pallet::<T>::generate_unique_hash(&clap);
let authority_id = authorities
.get(0usize)
.get(authority_index as usize)
.expect("first authority should exist");
let encoded_clap = clap.encode();
let signature = authority_id.sign(&encoded_clap).unwrap();
Pallet::<T>::slow_clap(RawOrigin::None.into(), clap, signature)?;
Pallet::<T>::trigger_nullification_for_benchmark();
let signature = authority_id.sign(&clap.encode())
.ok_or("couldn't make signature")?;
assert_eq!(<<T as pallet::Config>::Currency>::total_balance(&receiver), Default::default());
assert_eq!(ApplausesForTransaction::<T>::get(&storage_key), false);
let empty_bitmap = BitMap::new(1);
DisabledAuthorityIndexes::<T>::insert(session_index, empty_bitmap);
frame_system::Pallet::<T>::on_initialize(1u32.into());
let mut fake_received_clap =
BoundedBTreeSet::<AuthIndex, T::MaxAuthorities>::new();
assert_eq!(fake_received_clap.try_insert(1).unwrap(), true);
pallet::ReceivedClaps::<T>::insert(&next_storage_key, fake_received_clap);
}: _(RawOrigin::Signed(receiver_clone), network_id, session_index, transaction_hash, receiver_clone.clone(), amount)
assert_eq!(ApplauseDetails::<T>::get(&session_index, &args_hash).is_none(), true);
}: _(RawOrigin::None, clap, signature)
verify {
assert_eq!(ApplauseDetails::<T>::get(&session_index, &args_hash).is_some(), true);
assert_eq!(<<T as pallet::Config>::Currency>::total_balance(&receiver), amount);
assert_eq!(ApplausesForTransaction::<T>::get(&storage_key), true);
}
commit_block {
let session_index = T::ValidatorSet::session_index();
let network_id = NetworkIdOf::<T>::default();
prepare_evm_network::<T>(network_id);
let authorities = vec![T::AuthorityId::generate_pair(None)];
let bounded_authorities = WeakBoundedVec::<_, T::MaxAuthorities>::try_from(authorities.clone())
.map_err(|()| "more than the maximum number of keys provided")?;
Authorities::<T>::set(&session_index, bounded_authorities);
let authority_index = 0u32;
let block_commitment = BlockCommitment {
session_index,
authority_index,
network_id,
commitment: CommitmentDetails {
last_stored_block: 69,
commits: 420,
last_updated: 1337,
}
};
let authority_id = authorities
.get(authority_index as usize)
.expect("first authority should exist");
let signature = authority_id.sign(&block_commitment.encode())
.ok_or("couldn't make signature")?;
}: _(RawOrigin::None, block_commitment, signature)
verify {
let stored_commitment = BlockCommitments::<T>::get(&network_id)
.get(&authority_index)
.cloned()
.unwrap_or_default();
assert_eq!(stored_commitment.last_stored_block, 69);
assert_eq!(stored_commitment.commits, 1);
assert_eq!(stored_commitment.last_updated, 1337);
}
impl_benchmark_test_suite!(

View File

@ -0,0 +1,117 @@
use codec::{Decode, Encode};
use scale_info::TypeInfo;
use sp_core::RuntimeDebug;
use sp_std::collections::btree_map::BTreeMap;
use crate::AuthIndex;
pub type BucketId = u32;
pub type Bucket = u64;
#[derive(Clone, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo)]
pub struct BitMap {
buckets: BTreeMap<BucketId, Bucket>,
max_length: u32,
max_value: u32,
}
impl BitMap {
pub fn new(max_value: u32) -> Self {
let mut buckets: BTreeMap<BucketId, Bucket> = Default::default();
let max_length = (max_value >> Self::size_of_bucket()) + 1;
for bucket_id in 0..(max_length) {
buckets.insert(bucket_id, 0);
}
BitMap {
buckets,
max_length,
max_value,
}
}
pub fn size_of_bucket() -> u32 {
(core::mem::size_of::<Bucket>() * 8).trailing_zeros()
}
pub fn iter_buckets(&self) -> impl Iterator<Item = (&BucketId, &Bucket)> {
self.buckets.iter()
}
pub fn exists(&self, index: &AuthIndex) -> bool {
let (bucket_id, bit_position) = self.bitmap_positions(index);
self.buckets
.get(&bucket_id)
.map(|bucket| (bucket >> bit_position) & 1 == 1)
.unwrap_or_default()
}
pub fn set(&mut self, index: AuthIndex) {
let (bucket_id, bit_position) = self.bitmap_positions(&index);
if bucket_id < self.max_length {
let bucket = self.buckets.entry(bucket_id).or_insert(0);
*bucket |= 1 << bit_position;
}
}
pub fn unset(&mut self, index: AuthIndex) {
let (bucket_id, bit_position) = self.bitmap_positions(&index);
if let Some(bucket) = self.buckets.get_mut(&bucket_id) {
*bucket &= !(1 << bit_position);
if *bucket == 0 {
self.buckets.remove(&bucket_id);
}
}
}
pub fn get_bucket(&self, bucket_id: &BucketId) -> Bucket {
self.buckets.get(bucket_id).copied().unwrap_or_default()
}
pub fn count_ones(&self) -> u32 {
let zeros: u32 = self
.iter_buckets()
.map(|(_, bucket)| bucket.count_zeros())
.sum();
let total_bits = self.total_bits();
total_bits.saturating_sub(zeros)
}
pub fn bitor(self, rhs: Self) -> Self {
let (mut base, to_merge) = if self.buckets.len() < rhs.buckets.len() {
(rhs, self)
} else {
(self, rhs)
};
for (key, rhs_value) in to_merge.buckets {
base.buckets
.entry(key)
.and_modify(|lhs_value| *lhs_value |= rhs_value)
.or_insert(rhs_value);
}
base
}
pub fn max_value(&self) -> u32 {
self.max_value
}
fn total_bits(&self) -> u32 {
let size_of_bucket = Self::size_of_bucket();
let bucket_length: u32 = 1 << size_of_bucket;
self.max_length.saturating_mul(bucket_length)
}
fn bitmap_positions(&self, index: &AuthIndex) -> (u32, u32) {
let size_of_bucket = Self::size_of_bucket();
let bucket_length = 1 << size_of_bucket;
let bucket_id = index >> size_of_bucket;
let bit_position = index % bucket_length;
(bucket_id, bit_position)
}
}

View File

@ -1,9 +1,14 @@
use sp_runtime::SaturatedConversion;
use sp_staking::SessionIndex;
use crate::{
deserialisations::{
de_string_to_bytes, de_string_to_h256, de_string_to_u64, de_string_to_u64_pure,
de_string_to_vec_of_bytes,
},
Decode, Deserialize, Encode, RuntimeDebug, Vec, H256,
AuthIndex, BalanceOf, BlockCommitment, BlockCommitments, Call, Clap, CommitmentDetails, Config,
Decode, Deserialize, Encode, NetworkIdOf, RuntimeAppPublic, RuntimeDebug, SubmitTransaction,
Vec, COMMITMENT_DELAY_MILLIS, H256, LOG_TARGET,
};
const NUMBER_OF_TOPICS: usize = 3;
@ -40,6 +45,214 @@ pub struct Log {
pub removed: bool,
}
impl EvmResponseType {
fn prepare_block_commitment<T: Config>(
&self,
from_block: u64,
authority_index: AuthIndex,
session_index: SessionIndex,
network_id: NetworkIdOf<T>,
) -> BlockCommitment<NetworkIdOf<T>> {
let last_updated = sp_io::offchain::timestamp().unix_millis();
BlockCommitment {
session_index,
authority_index,
network_id,
commitment: CommitmentDetails {
last_stored_block: from_block,
last_updated,
commits: 420,
},
}
}
fn prepare_clap<T: Config>(
&self,
authority_index: AuthIndex,
session_index: SessionIndex,
network_id: NetworkIdOf<T>,
log: &Log,
) -> Clap<T::AccountId, NetworkIdOf<T>, BalanceOf<T>> {
Clap {
authority_index,
session_index,
network_id,
removed: log.removed,
receiver: T::AccountId::decode(&mut &log.topics[1][0..32])
.expect("32 bytes always construct an AccountId32"),
amount: u128::from_be_bytes(
log.topics[2][16..32]
.try_into()
.expect("amount is valid hex; qed"),
)
.saturated_into::<BalanceOf<T>>(),
transaction_hash: log.transaction_hash.clone().expect("tx hash exists; qed"),
block_number: log.block_number.expect("block number exists; qed"),
}
}
fn iter_claps_from_logs<T: Config>(
&self,
authority_index: AuthIndex,
session_index: SessionIndex,
network_id: NetworkIdOf<T>,
) -> Vec<Clap<T::AccountId, NetworkIdOf<T>, BalanceOf<T>>> {
match self {
EvmResponseType::TransactionLogs(evm_logs) => evm_logs
.iter()
.filter_map(move |log| {
log.is_sufficient().then(|| {
self.prepare_clap::<T>(authority_index, session_index, network_id, log)
})
})
.collect(),
EvmResponseType::BlockNumber(_) => Vec::new(),
}
}
fn sign_and_submit_claps<T: Config>(
&self,
authority_index: AuthIndex,
authority_key: T::AuthorityId,
session_index: SessionIndex,
network_id: NetworkIdOf<T>,
) {
let claps = self.iter_claps_from_logs::<T>(authority_index, session_index, network_id);
let claps_len = claps.len();
log::info!(
target: LOG_TARGET,
"👻 Found {:?} claps for network {:?}",
claps_len,
network_id,
);
for (clap_index, clap) in claps.iter().enumerate() {
let signature = match authority_key.sign(&clap.encode()) {
Some(signature) => signature,
None => {
log::info!(
target: LOG_TARGET,
"👻 Clap #{} signing failed from authority #{:?} for network {:?}",
clap_index,
authority_index,
network_id,
);
return;
}
};
let call = Call::slow_clap {
clap: clap.clone(),
signature,
};
if let Err(e) =
SubmitTransaction::<T, Call<T>>::submit_unsigned_transaction(call.into())
{
log::info!(
target: LOG_TARGET,
"👻 Failed to submit clap #{} from authority #{:?} for network {:?}: {:?}",
clap_index,
authority_index,
network_id,
e,
);
}
}
}
fn sign_and_submit_block_commitment<T: Config>(
&self,
from_block: u64,
authority_index: AuthIndex,
authority_key: T::AuthorityId,
session_index: SessionIndex,
network_id: NetworkIdOf<T>,
) {
let block_commitment = self.prepare_block_commitment::<T>(
from_block,
authority_index,
session_index,
network_id,
);
let stored_last_updated = BlockCommitments::<T>::get(&network_id)
.get(&authority_index)
.map(|details| details.last_updated)
.unwrap_or_default();
let current_last_updated = block_commitment
.commitment
.last_updated
.saturating_sub(COMMITMENT_DELAY_MILLIS);
if current_last_updated < stored_last_updated {
return;
}
log::info!(
target: LOG_TARGET,
"👻 New block commitment from authority #{:?} for network {:?}",
authority_index,
network_id,
);
let signature = match authority_key.sign(&block_commitment.encode()) {
Some(signature) => signature,
None => {
log::info!(
target: LOG_TARGET,
"👻 Block commitment signing failed from authority #{:?} for network {:?}",
authority_index,
network_id,
);
return;
}
};
let call = Call::commit_block {
block_commitment,
signature,
};
if let Err(e) = SubmitTransaction::<T, Call<T>>::submit_unsigned_transaction(call.into()) {
log::info!(
target: LOG_TARGET,
"👻 Failed to submit block commitment from authority #{:?} for network {:?}: {:?}",
authority_index,
network_id,
e,
);
}
}
pub fn sign_and_submit<T: Config>(
&self,
from_block: u64,
authority_index: AuthIndex,
authority_key: T::AuthorityId,
session_index: SessionIndex,
network_id: NetworkIdOf<T>,
) {
match self {
EvmResponseType::TransactionLogs(_) => self.sign_and_submit_claps::<T>(
authority_index,
authority_key,
session_index,
network_id,
),
EvmResponseType::BlockNumber(_) => self.sign_and_submit_block_commitment::<T>(
from_block,
authority_index,
authority_key,
session_index,
network_id,
),
}
}
}
impl Log {
pub fn is_sufficient(&self) -> bool {
self.transaction_hash.is_some()

File diff suppressed because it is too large Load Diff

View File

@ -9,7 +9,7 @@ use pallet_session::historical as pallet_session_historical;
use sp_runtime::{
curve::PiecewiseLinear,
testing::{TestXt, UintAuthorityId},
traits::ConvertInto,
traits::{AtLeast32BitUnsigned, ConvertInto},
Permill,
};
use sp_staking::{
@ -19,8 +19,8 @@ use sp_staking::{
use sp_runtime::BuildStorage;
use crate as slow_clap;
use crate::Config;
use crate::{self as slow_clap};
use crate::{Config, ExposureListener};
type Block = frame_system::mocking::MockBlock<Runtime>;
@ -36,17 +36,13 @@ frame_support::construct_runtime!(
);
parameter_types! {
pub static Validators: Option<Vec<u64>> = Some(vec![
1,
2,
3,
]);
pub static FixedValidators: Vec<u64> = vec![0, 1, 2, 3];
}
pub struct TestSessionManager;
impl pallet_session::SessionManager<u64> for TestSessionManager {
fn new_session(_new_index: SessionIndex) -> Option<Vec<u64>> {
Validators::mutate(|l| l.take())
Some(FixedValidators::get())
}
fn end_session(_: SessionIndex) {}
fn start_session(_: SessionIndex) {}
@ -54,17 +50,14 @@ impl pallet_session::SessionManager<u64> for TestSessionManager {
impl pallet_session::historical::SessionManager<u64, u64> for TestSessionManager {
fn new_session(_new_index: SessionIndex) -> Option<Vec<(u64, u64)>> {
Validators::mutate(|l| {
l.take()
.map(|validators| validators.iter().map(|v| (*v, *v)).collect())
})
Some(FixedValidators::get().iter().map(|l| (*l, *l)).collect())
}
fn end_session(_: SessionIndex) {}
fn start_session(_: SessionIndex) {}
}
type IdentificationTuple = (u64, u64);
type Offence = crate::ThrottlingOffence<IdentificationTuple>;
type Offence = crate::SlowClapOffence<IdentificationTuple>;
parameter_types! {
pub static Offences: Vec<(Vec<u64>, Offence)> = vec![];
@ -90,7 +83,7 @@ pub fn new_test_ext() -> sp_io::TestExternalities {
let mut result = sp_io::TestExternalities::new(t);
result.execute_with(|| {
for i in 1..=3 {
for i in 0..=3 {
System::inc_providers(&i);
assert_eq!(
Session::set_keys(RuntimeOrigin::signed(i), i.into(), vec![],),
@ -174,6 +167,33 @@ impl pallet_balances::Config for Runtime {
type WeightInfo = ();
}
type Balance = u64;
pub struct TestExposureListener;
impl ExposureListener<Balance, u64> for TestExposureListener
where
Balance: AtLeast32BitUnsigned + From<u64>,
{
fn get_account_by_index(index: usize) -> Option<u64> {
FixedValidators::get().get(index).copied()
}
fn get_total_exposure() -> Balance {
1_000_000_000u64.into()
}
fn get_validator_exposure(validator: &u64) -> Balance {
match validator {
0 => 250_000_000u64,
1 => 200_000_000u64,
2 => 250_000_000u64,
3 => 300_000_000u64,
_ => 0,
}
.into()
}
}
impl Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type AuthorityId = UintAuthorityId;
@ -184,13 +204,13 @@ impl Config for Runtime {
type BlockNumberProvider = System;
type ReportUnresponsiveness = OffenceHandler;
type DisabledValidators = Session;
type ExposureListener = TestExposureListener;
type MaxAuthorities = ConstU32<5>;
type ApplauseThreshold = ConstU32<50>;
type OffenceThreshold = ConstU32<0>;
type ApplauseThreshold = ConstU32<500_000_000>;
type UnsignedPriority = ConstU64<{ 1 << 20 }>;
type HistoryDepth = HistoryDepth;
type MinAuthoritiesNumber = ConstU32<2>;
type MinAuthoritiesNumber = ConstU32<1>;
type WeightInfo = ();
}
@ -209,32 +229,7 @@ pub fn advance_session() {
let now = System::block_number().max(1);
System::set_block_number(now + 1);
Session::rotate_session();
let session_index = Session::current_index();
let authorities = Session::validators()
.into_iter()
.map(UintAuthorityId)
.collect();
SlowClap::set_test_authorities(session_index, authorities);
assert_eq!(session_index, (now / Period::get()) as u32);
}
pub fn advance_session_with_authority(authority: u64) {
let now = System::block_number().max(1);
System::set_block_number(now + 1);
Session::rotate_session();
let session_index = Session::current_index();
SlowClap::set_test_authorities(
session_index,
vec![
UintAuthorityId::from(authority),
UintAuthorityId::from(69),
UintAuthorityId::from(420),
UintAuthorityId::from(1337),
],
);
assert_eq!(session_index, (now / Period::get()) as u32);
}

File diff suppressed because it is too large Load Diff

View File

@ -48,70 +48,7 @@ use core::marker::PhantomData;
pub trait WeightInfo {
fn slow_clap() -> Weight;
fn self_applause()-> Weight;
}
/// Weight functions for `ghost_slow_clap`.
pub struct SubstrateWeight<T>(PhantomData<T>);
impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
/// Storage: `GhostSlowClaps::Authorities` (r:1 w:0)
/// Proof: `GhostSlowClaps::Authorities` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::ReceivedClaps` (r:1 w:1)
/// Proof: `GhostSlowClaps::ReceivedClaps` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::ClapsInSession` (r:1 w:1)
/// Proof: `GhostSlowClaps::ClapsInSession` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::ApplausesForTransaction` (r:1 w:1)
/// Proof: `GhostSlowClaps::ApplausesForTransaction` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::NullifyNeeded` (r:1 w:0)
/// Proof: `GhostNetworks::NullifyNeeded` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::Networks` (r:1 w:0)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::GatekeeperAmount` (r:1 w:1)
/// Proof: `GhostNetworks::GatekeeperAmount` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::BridgedImbalance` (r:1 w:1)
/// Proof: `GhostNetworks::BridgedImbalance` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::AccumulatedCommission` (r:1 w:1)
/// Proof: `GhostNetworks::AccumulatedCommission` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `System::Account` (r:1 w:1)
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
fn slow_clap() -> Weight {
// Proof Size summary in bytes:
// Measured: `355`
// Estimated: `3820`
// Minimum execution time: 213_817_000 picoseconds.
Weight::from_parts(216_977_000, 0)
.saturating_add(Weight::from_parts(0, 3820))
.saturating_add(T::DbWeight::get().reads(10))
.saturating_add(T::DbWeight::get().writes(7))
}
/// Storage: `GhostSlowClaps::ReceivedClaps` (r:1 w:0)
/// Proof: `GhostSlowClaps::ReceivedClaps` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::Authorities` (r:1 w:0)
/// Proof: `GhostSlowClaps::Authorities` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::ApplausesForTransaction` (r:1 w:1)
/// Proof: `GhostSlowClaps::ApplausesForTransaction` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::NullifyNeeded` (r:1 w:0)
/// Proof: `GhostNetworks::NullifyNeeded` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::Networks` (r:1 w:0)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::GatekeeperAmount` (r:1 w:1)
/// Proof: `GhostNetworks::GatekeeperAmount` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::BridgedImbalance` (r:1 w:1)
/// Proof: `GhostNetworks::BridgedImbalance` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::AccumulatedCommission` (r:1 w:1)
/// Proof: `GhostNetworks::AccumulatedCommission` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `System::Account` (r:1 w:1)
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
fn self_applause() -> Weight {
// Proof Size summary in bytes:
// Measured: `655`
// Estimated: `4120`
// Minimum execution time: 210_676_000 picoseconds.
Weight::from_parts(212_905_000, 0)
.saturating_add(Weight::from_parts(0, 4120))
.saturating_add(T::DbWeight::get().reads(9))
.saturating_add(T::DbWeight::get().writes(5))
}
fn commit_block()-> Weight;
}
impl WeightInfo for () {
@ -145,32 +82,8 @@ impl WeightInfo for () {
.saturating_add(RocksDbWeight::get().reads(10))
.saturating_add(RocksDbWeight::get().writes(7))
}
/// Storage: `GhostSlowClaps::ReceivedClaps` (r:1 w:0)
/// Proof: `GhostSlowClaps::ReceivedClaps` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::Authorities` (r:1 w:0)
/// Proof: `GhostSlowClaps::Authorities` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::ApplausesForTransaction` (r:1 w:1)
/// Proof: `GhostSlowClaps::ApplausesForTransaction` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::NullifyNeeded` (r:1 w:0)
/// Proof: `GhostNetworks::NullifyNeeded` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::Networks` (r:1 w:0)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::GatekeeperAmount` (r:1 w:1)
/// Proof: `GhostNetworks::GatekeeperAmount` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::BridgedImbalance` (r:1 w:1)
/// Proof: `GhostNetworks::BridgedImbalance` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::AccumulatedCommission` (r:1 w:1)
/// Proof: `GhostNetworks::AccumulatedCommission` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `System::Account` (r:1 w:1)
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
fn self_applause() -> Weight {
// Proof Size summary in bytes:
// Measured: `655`
// Estimated: `4120`
// Minimum execution time: 210_676_000 picoseconds.
Weight::from_parts(212_905_000, 0)
.saturating_add(Weight::from_parts(0, 4120))
.saturating_add(RocksDbWeight::get().reads(9))
.saturating_add(RocksDbWeight::get().writes(5))
fn commit_block()-> Weight {
Default::default()
}
}

View File

@ -1,6 +1,6 @@
[package]
name = "ghost-traits"
version = "0.3.23"
version = "0.3.26"
license.workspace = true
authors.workspace = true
edition.workspace = true

View File

@ -0,0 +1,7 @@
use sp_runtime::traits::AtLeast32BitUnsigned;
pub trait ExposureListener<Balance: AtLeast32BitUnsigned, AccountId> {
fn get_account_by_index(index: usize) -> Option<AccountId>;
fn get_total_exposure() -> Balance;
fn get_validator_exposure(index: &AccountId) -> Balance;
}

View File

@ -1,3 +1,4 @@
#![cfg_attr(not(feature = "std"), no_std)]
pub mod exposure;
pub mod networks;

View File

@ -1,6 +1,6 @@
[package]
name = "casper-runtime"
version = "3.5.36"
version = "3.5.34"
build = "build.rs"
description = "Runtime of the Casper Network"
edition.workspace = true
@ -88,6 +88,7 @@ ghost-networks = { workspace = true }
ghost-claims = { workspace = true }
ghost-slow-clap = { workspace = true }
ghost-sudo = { workspace = true }
ghost-traits = { workspace = true }
casper-runtime-constants = { workspace = true }
runtime-common = { workspace = true }
primitives = { workspace = true }

View File

@ -1,6 +1,8 @@
use super::*;
use frame_support::{dispatch::DispatchResultWithPostInfo, traits::PrivilegeCmp};
use ghost_traits::exposure::ExposureListener;
use pallet_alliance::{ProposalIndex, ProposalProvider};
use primitives::Balance;
use sp_runtime::DispatchError;
use sp_std::{cmp::Ordering, marker::PhantomData};
@ -76,6 +78,36 @@ impl PrivilegeCmp<OriginCaller> for EqualOrGreatestRootCmp {
}
}
/// Used to get the exposure information out of staking pallet directly.
pub struct StakingExposureListener<T>(PhantomData<T>);
impl<T> ExposureListener<Balance, AccountIdOf<T>> for StakingExposureListener<T>
where
T: pallet_session::Config + pallet_staking::Config + frame_system::Config,
u128: From<T::CurrencyBalance>,
AccountIdOf<T>: From<<T as pallet_session::Config>::ValidatorId>,
{
fn get_account_by_index(index: usize) -> Option<AccountIdOf<T>> {
pallet_session::Pallet::<T>::validators()
.get(index)
.map(|validator| {
let account_id: AccountIdOf<T> = validator.clone().into();
account_id
})
}
fn get_total_exposure() -> Balance {
let era = pallet_staking::Pallet::<T>::current_era().unwrap_or_default();
pallet_staking::Pallet::<T>::eras_total_stake(era).into()
}
fn get_validator_exposure(validator: &AccountIdOf<T>) -> Balance {
let era = pallet_staking::Pallet::<T>::current_era().unwrap_or_default();
pallet_staking::EraInfo::<T>::get_full_exposure(era, validator)
.total
.into()
}
}
#[cfg(feature = "runtime-benchmarks")]
pub mod benchmarks {
use super::*;

View File

@ -78,7 +78,7 @@ mod genesis_config_presets;
mod impls;
mod weights;
pub use impls::{AllianceProposalProvider, EqualOrGreatestRootCmp};
pub use impls::{AllianceProposalProvider, EqualOrGreatestRootCmp, StakingExposureListener};
// Governance configuration.
pub mod cult;
@ -117,8 +117,8 @@ pub const VERSION: RuntimeVersion = RuntimeVersion {
spec_name: create_runtime_str!("casper"),
impl_name: create_runtime_str!("casper-svengali"),
authoring_version: 0,
spec_version: 6,
impl_version: 4,
spec_version: 3,
impl_version: 1,
apis: RUNTIME_API_VERSIONS,
transaction_version: 1,
state_version: 1,
@ -1058,11 +1058,8 @@ impl ghost_claims::Config<CultCollectiveInstance> for Runtime {
}
parameter_types! {
// will be used in `Perbill::from_percent()`
pub const ApplauseThreshold: u32 = 66;
// will be used in `Perbill::from_percent()`
pub const OffenceThreshold: u32 = 5;
// 4 validators should be functional if 1 is offline
// will be used in `Perbill::from_parts()`
pub const ApplauseThreshold: u32 = 500_000_000;
pub const MinAuthoritiesNumber: u32 = 5;
pub const SlowClapUnsignedPriority: TransactionPriority = TransactionPriority::MAX;
pub const SlowClapHistoryDepth: sp_staking::SessionIndex =
@ -1079,10 +1076,10 @@ impl ghost_slow_clap::Config for Runtime {
type BlockNumberProvider = System;
type ReportUnresponsiveness = Offences;
type DisabledValidators = Session;
type ExposureListener = StakingExposureListener<Runtime>;
type MaxAuthorities = MaxAuthorities;
type ApplauseThreshold = ApplauseThreshold;
type OffenceThreshold = OffenceThreshold;
type UnsignedPriority = SlowClapUnsignedPriority;
type HistoryDepth = SlowClapHistoryDepth;
type MinAuthoritiesNumber = MinAuthoritiesNumber;

View File

@ -191,6 +191,18 @@ impl<T: frame_system::Config> ghost_networks::WeightInfo for WeightInfo<T> {
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_avg_block_speed() -> Weight {
// Proof Size summary in bytes:
// Measured: `302`
// Estimated: `3767`
// Minimum execution time: 49_579_000 picoseconds.
Weight::from_parts(51_126_000, 0)
.saturating_add(Weight::from_parts(0, 3767))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn remove_network() -> Weight {
// Proof Size summary in bytes:
// Measured: `302`

View File

@ -76,34 +76,7 @@ impl<T: frame_system::Config> ghost_slow_clap::WeightInfo for WeightInfo<T> {
.saturating_add(T::DbWeight::get().reads(10))
.saturating_add(T::DbWeight::get().writes(7))
}
/// Storage: `GhostSlowClaps::Authorities` (r:2 w:0)
/// Proof: `GhostSlowClaps::Authorities` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::ReceivedClaps` (r:2 w:0)
/// Proof: `GhostSlowClaps::ReceivedClaps` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::ClapsInSession` (r:1 w:0)
/// Proof: `GhostSlowClaps::ClapsInSession` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::ApplausesForTransaction` (r:1 w:1)
/// Proof: `GhostSlowClaps::ApplausesForTransaction` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::NullifyNeeded` (r:1 w:0)
/// Proof: `GhostNetworks::NullifyNeeded` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::Networks` (r:1 w:0)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::GatekeeperAmount` (r:1 w:1)
/// Proof: `GhostNetworks::GatekeeperAmount` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::BridgedImbalance` (r:1 w:1)
/// Proof: `GhostNetworks::BridgedImbalance` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::AccumulatedCommission` (r:1 w:1)
/// Proof: `GhostNetworks::AccumulatedCommission` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `System::Account` (r:1 w:1)
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
fn self_applause() -> Weight {
// Proof Size summary in bytes:
// Measured: `861`
// Estimated: `6801`
// Minimum execution time: 258_510_000 picoseconds.
Weight::from_parts(262_353_000, 0)
.saturating_add(Weight::from_parts(0, 6801))
.saturating_add(T::DbWeight::get().reads(12))
.saturating_add(T::DbWeight::get().writes(5))
fn commit_block()-> Weight {
Default::default()
}
}

View File

@ -81,18 +81,20 @@ extract_seed() {
}
downgrade_compiler_if_needed() {
echo "[+] fetching the latest ghost-node source code"
git switch main
git pull origin main
# TODO: uncomment later
# echo "[+] fetching the latest ghost-node source code"
# git switch main
# git pull origin main
# 1.86.0 works fine, tested with:
# 1.83.0 works fine, tested with:
# ...
# 1.87.0 throws errors during compilation
# 1.88.0 throws errors during compilation
LATEST_TESTED_VERSION=86
LATEST_TESTED_VERSION=83
cargo_version=$(cargo --version | cut -d'.' -f2)
if [ "$cargo_version" -gt "$LATEST_TESTED_VERSION" ]; then
echo "[+] downgrading rustc compiler version to 1.86.0"
rustup default 1.86.0
echo "[+] downgrading rustc compiler version to 1.83.0"
rustup default 1.83.0
toolchain_name=$(rustup show | grep default | head -n 1 | cut -d' ' -f1)
rustup target add wasm32-unknown-unknown --toolchain $toolchain_name
rustup component add rust-src --toolchain $toolchain_name

View File

@ -205,6 +205,7 @@ fn casper_testnet_evm_networks() -> Vec<(u32, Vec<u8>)> {
finality_delay: 69u64,
rate_limit_delay: 5_000u64,
block_distance: 20u64,
avg_block_speed: 12_000,
network_type: ghost_networks::NetworkType::Evm,
gatekeeper: "0xc85129A097773B7F8970a7364c928C05f265E6A1".into(),
topic_name: "0x7ab52ec05c331e6257a3d705d6bea6e4c27277351764ad139209e06b203811a6".into(),