Skip to content

Commit

Permalink
Debugging, Testing, and Cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
Tjemmmic committed Aug 14, 2024
1 parent d244cf6 commit c71a1ea
Show file tree
Hide file tree
Showing 15 changed files with 118 additions and 161 deletions.
2 changes: 1 addition & 1 deletion avs/incredible-squaring-avs/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ fn main() {
if full_path.exists() {
println!("cargo:rerun-if-changed={}", full_path.display());

let status = Command::new("forge")
let status = Command::new("/home/tjemmmic/.foundry/bin/forge")
.current_dir(&full_path)
.arg("build")
.status()
Expand Down
2 changes: 1 addition & 1 deletion avs/tangle-avs/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ fn main() {
if full_path.exists() {
println!("cargo:rerun-if-changed={}", full_path.display());

let status = Command::new("forge")
let status = Command::new("/home/tjemmmic/.foundry/bin/forge")
.current_dir(&full_path)
.arg("build")
.status()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;

import "./eigenlayer-contracts/src/contracts/libraries/BytesLib.sol";
import "./ITangleValidatorTaskManager.sol";
import "./eigenlayer-middleware/src/ServiceManagerBase.sol";
import "eigenlayer-middleware/lib/eigenlayer-contracts/src/contracts/libraries/BytesLib.sol";
import "src/ITangleValidatorTaskManager.sol";
import "eigenlayer-middleware/src/ServiceManagerBase.sol";

/**
* @title Primary entrypoint for procuring services from TangleValidator.
Expand Down Expand Up @@ -32,7 +32,6 @@ contract TangleValidatorServiceManager is ServiceManagerBase {
)
ServiceManagerBase(
_avsDirectory,
IRewardsCoordinator(address(0)), // inc-sq doesn't need to deal with payments
_registryCoordinator,
_stakeRegistry
)
Expand Down
8 changes: 8 additions & 0 deletions test-utils/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@ license.workspace = true
homepage.workspace = true
repository.workspace = true

#[lib]
#name = "test_utils"
#path = "src/lib.rs"
#
#[[bin]]
#name = "incredible_squaring"
#path = "src/incredible_squaring.rs"

[dependencies]
alloy-abi.workspace = true
alloy-contract.workspace = true
Expand Down
2 changes: 1 addition & 1 deletion test-utils/keystore/bls
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"pub_key":{"x":"0x13b15d57e069eee24b23c82947dc6cd57a7c87e965c5dc325ca1e770dd52ad01","y":"0x5d262729c016f000f161c8edef2b55061520c6786042ef93fa61cea057e5b8f"},"crypto":{"encrypted_data":"7FQ+MQN6ZIQaTK20rdiVunAGtZE3SP5fWkKn54spoled8Z4c0+xd06/Hq43Kp3YI","nonce":"qVgmzWcYA4GtWKzP","password_hash":"JHNjcnlwdCRsbj0xNyxyPTgscD0xJHdCdWtNcU5NMmZkenMxaGxwczRVOXckZVRLQUtnbHhHK2lVZlBBakZ5K0tkMXYxNDRveUl6NUUzS2hmT3kzNUNCTQ=="}}
{"pub_key":{"x":"0x2ed159b38ebb1317b82c3a816202ff8b39788b7996164384f7b79eb06ccdb330","y":"0x7a559aedbd3b933c7dd94234b805419be6a22065e646d23b4b1fe8e92fcd823"},"crypto":{"encrypted_data":"MiC+DCC00z+Lg4J9HGfzZqOPnghgiqJiXQ2982hWSnBoLwdvR4+U+YzG7SIXXWh/","nonce":"q+YU8mhCLsll8KDk","password_hash":"JHNjcnlwdCRsbj0xNyxyPTgscD0xJHk5bUR4NGFxM0hmYXU4Ti94U3BiOWckZGhJYWpid1JwN3ZidmQvMDR1VTlITDc3cVNNNkd4YWpYcWZLSWVGb0ZxRQ=="}}
2 changes: 1 addition & 1 deletion test-utils/keystore/ecdsa
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"address":"0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266","crypto":{"Cipher":"aes-128-ctr","CipherText":"664c7c0cfe1fd5c56d8724fb2b6dab05b9586055d782a498dadce199b58dbfce","CipherParams":{"IV":"be94caa22073e77a88139e12552516d8"},"KDF":"scrypt","KDFParams":{"n":17,"r":8,"p":1,"dklen":32,"salt":"e79a8ed192e4ed4c06c7d436280a16465ee8fa6b0d4379c0776d37911c050b0c"},"MAC":"6877ae9c653c0e938ee8012eeee3371f03c3584564223a5c7113552e452ae4c3"},"id":"0e1a54e2-b697-4c66-9b04-a4e3dc733f12","version":"3"}
{"address":"0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266","crypto":{"Cipher":"aes-128-ctr","CipherText":"1113254d033cc52729222bd5742459a4d054a449aff3def44ae3018fb8dc7748","CipherParams":{"IV":"7e85c58ecd9e5ecb8fc36fdaac3aab96"},"KDF":"scrypt","KDFParams":{"n":17,"r":8,"p":1,"dklen":32,"salt":"f480c3532ddbd9f2c23be95ad94072d3df15284c556d3ba6b0b6fa286ece18e0"},"MAC":"d55830a172e2ac50764a4426c96fe1f9e68ded4470cd234bc0b44a7eea981643"},"id":"99d8665f-eb45-49d0-936d-c69965cb5835","version":"3"}
25 changes: 25 additions & 0 deletions test-utils/scripts/avs_rebuild_contracts.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#!/bin/bash

# Define the directories
DIR1="./../avs/incredible-squaring-avs/contracts"
DIR2="./../avs/tangle-avs/contract"

# Function to run forge commands in a directory
run_forge_commands() {
local dir=$1
echo "Running forge commands in $dir"
cd "$dir" || exit
forge clean
forge build
cd - || exit
}

# Run forge commands in both directories
run_forge_commands "$DIR1"
run_forge_commands "$DIR2"

# Run cargo test in the starting directory
#echo "Running cargo test in the current directory"
#cargo test

echo "Rebuilt all AVS Smart Contracts!"
File renamed without changes.
4 changes: 0 additions & 4 deletions test-utils/src/anvil/abi.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
use alloy_sol_types::abi;
use alloy_sol_types::abi::Token;
use sha3::{Digest, Keccak256};

/// Macro that acts as the Rust equivalent of Solidity's `abi.encodeWithSelector`. Returns [alloy_primitives::Bytes]
#[macro_export]
macro_rules! encode_params {
Expand Down
73 changes: 6 additions & 67 deletions test-utils/src/anvil/testnet/incredible_squaring.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,15 @@
use crate::encode_params;
use alloy::signers::Signer;
use alloy_primitives::{address, Address, Bytes, Keccak256, Uint, U256};
use alloy_provider::network::{TransactionBuilder, TxSigner};
use alloy_primitives::{address, Address, Bytes, Keccak256, U256};
use alloy_provider::{Provider, ProviderBuilder};
use alloy_rpc_types_eth::BlockId;
use alloy_signer_local::PrivateKeySigner;
use alloy_sol_types::{
abi::Encoder,
abi::{self, token::*},
private::SolTypeValue,
SolValue, Word,
};
use alloy_transport_ws::WsConnect;
use alloy_sol_types::{abi, SolValue};
use anvil::spawn;
use ark_bn254::{Fq as F, Fr, G1Affine, G2Affine, G2Projective};
use eigen_contracts::{
RegistryCoordinator::{OperatorSetParam, StrategyParams},
*,
};
use gadget_common::subxt_signer::bip39::rand_core::OsRng;
use incredible_squaring_avs::avs::{
IncredibleSquaringServiceManager, IncredibleSquaringTaskManager,
};
use k256::{ecdsa::VerifyingKey, elliptic_curve::SecretKey};
use std::{path::Path, time::Duration};
use url::Url;

pub static BLS_PASSWORD: &str = "BLS_PASSWORD";
Expand All @@ -46,7 +32,7 @@ pub async fn run_anvil_testnet() -> ContractAddresses {
// Initialize the logger
let _ = env_logger::try_init();

let (api, mut handle) = spawn(
let (api, handle) = spawn(
anvil::NodeConfig::test()
.with_port(8545)
.with_print_logs(true)
Expand Down Expand Up @@ -81,7 +67,7 @@ pub async fn run_anvil_testnet() -> ContractAddresses {
let _gas_price = provider.get_gas_price().await.unwrap();

// Empty address for initial deployment of all contracts
let empty_address = Address::default();
let _empty_address = Address::default();

// let strategy_manager_addr = address!("Dc64a140Aa3E981100a9becA4E685f962f0cF6C9");
// let delegation_manager_addr = address!("Cf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9");
Expand Down Expand Up @@ -477,7 +463,7 @@ pub async fn run_anvil_testnet() -> ContractAddresses {
for j in 0..number_of_quorums {
quorums_strategy_params.push(Vec::<StrategyParams>::new());
quorums_minimum_stake.push(0);
for k in 0..number_of_strategies {
for _k in 0..number_of_strategies {
quorums_strategy_params[j].push(StrategyParams {
strategy: strategies[j],
multiplier: 1,
Expand All @@ -488,37 +474,7 @@ pub async fn run_anvil_testnet() -> ContractAddresses {
// Function with signature initialize(address,address,address,address,uint256,(uint32,uint16,uint16)[],uint96[],(address,uint96)[][]) and selector 0xdd8283f3.
let function_signature = "initialize(address,address,address,address,uint256,(uint32,uint16,uint16)[],uint96[],(address,uint96)[][])";

let single_test = 0.tokenize();
println!("Word Tokenize: {:?}", single_test);
let vec_test = quorum_operator_set_params.tokenize();
println!("Vec Tokenize: {:?}", vec_test);

let encoded_word = abi::encode(&single_test);

let encoded_vec = abi::encode(&vec_test);

println!(
"Quorums Strategy Params: Strategy: {:?} Multiplier: {:?}",
quorums_strategy_params[0][0].strategy, quorums_strategy_params[0][0].multiplier
);
println!("Quorum Operator Set Params: Max Operators: {:?}, Kick BIPs of Operator Stake: {:?}, Kick BIPs of Total Stake: {:?}", quorum_operator_set_params[0].maxOperatorCount, quorum_operator_set_params[0].kickBIPsOfOperatorStake, quorum_operator_set_params[0].kickBIPsOfTotalStake);
println!("Quorums Minimum Stake: {:?}", quorums_minimum_stake);

// let mut hasher = Keccak256::new();
// hasher.update(function_signature);
// let function_selector = &hasher.finalize()[..4];
// let mut data = Vec::from(function_selector);
// data.extend_from_slice(&abi::encode(&pausers[0].tokenize()));
// data.extend_from_slice(&abi::encode(&pausers[0].tokenize()));
// data.extend_from_slice(&abi::encode(&pausers[0].tokenize()));
// data.extend_from_slice(&abi::encode(&pausers[1].tokenize()));
// data.extend_from_slice(&abi::encode(&0.tokenize()));
// data.extend_from_slice(&abi::encode(&quorum_operator_set_params.tokenize()));
// data.extend_from_slice(&abi::encode(&quorums_minimum_stake.tokenize()));
// data.extend_from_slice(&abi::encode(&quorums_strategy_params.tokenize()));
// let encoded_data = alloy_primitives::Bytes::from(data);

let encoded_data = encode_params!(
let _encoded_data = encode_params!(
function_signature,
pausers[0],
pausers[0],
Expand All @@ -529,23 +485,6 @@ pub async fn run_anvil_testnet() -> ContractAddresses {
quorums_minimum_stake,
quorums_strategy_params
);
// let registry_coordinator_upgrade = incredible_squaring_proxy_admin
// .upgradeAndCall(
// registry_coordinator_addr,
// registry_coordinator_implementation_addr,
// encoded_data,
// )
// // .from(dev_account)
// .send()
// .await
// .unwrap()
// .get_receipt()
// .await
// .unwrap();
// log::info!(
// "Registry Coordinator Upgrade Receipt: {:?}",
// registry_coordinator_upgrade
// );

let registry_coordinator_upgrade = incredible_squaring_proxy_admin
.upgrade(
Expand Down
12 changes: 11 additions & 1 deletion test-utils/src/incredible_squaring.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#[allow(dead_code)]
use crate::anvil::testnet::incredible_squaring::*;
use alloy_provider::Provider;
use alloy_provider::ProviderBuilder;
Expand All @@ -7,6 +8,15 @@ use incredible_squaring_avs::operator::*;
use k256::ecdsa::SigningKey;
use k256::elliptic_curve::SecretKey;

#[tokio::main]
async fn main() {
let _ = env_logger::try_init();
run_full_incredible_squaring_test().await;
}

/// THIS FUNCTION IS FOR TESTING ONLY
///
/// Runs the Incredible Squaring Testnet and then creates an Operator that connects and registers.
async fn run_full_incredible_squaring_test() {
let _ = env_logger::try_init();

Expand Down Expand Up @@ -70,7 +80,7 @@ async fn run_full_incredible_squaring_test() {
let operator_info_service = OperatorInfoService {};

let hex_key =
hex::decode("59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d").unwrap();
hex::decode("ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80").unwrap();
let secret_key = SecretKey::from_slice(&hex_key).unwrap();
let signing_key = SigningKey::from(secret_key.clone());
let signer = EigenGadgetSigner {
Expand Down
49 changes: 38 additions & 11 deletions utils/src/avs_registry/writer.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
#![allow(async_fn_in_trait)]

use super::{AvsRegistryContractManager, AvsRegistryContractResult};
use crate::crypto::bls::{G1Point, KeyPair};
use crate::crypto::bls::{g1_point_to_ark_point, g1_point_to_g1_projective, G1Point, KeyPair};
use crate::crypto::bn254::get_g2_generator;
use crate::crypto::ecdsa::ToAddress;
use crate::el_contracts::reader::ElReader;
use crate::{types::*, Config};
Expand All @@ -10,6 +11,8 @@ use alloy_provider::Provider;
use alloy_rpc_types::TransactionReceipt;
use alloy_signer::k256::ecdsa;
use alloy_signer::Signer as alloySigner;
use ark_ec::pairing::Pairing;
use ark_ec::CurveGroup;
use eigen_contracts::RegistryCoordinator;
use eigen_contracts::RegistryCoordinator::SignatureWithSaltAndExpiry;
use k256::ecdsa::VerifyingKey;
Expand Down Expand Up @@ -58,7 +61,6 @@ impl<T: Config> AvsRegistryChainWriterTrait for AvsRegistryContractManager<T> {
quorum_numbers: Bytes,
socket: String,
) -> AvsRegistryContractResult<TransactionReceipt> {
log::info!("Signing Key: {:?}", operator_ecdsa_private_key);
let operator_addr = operator_ecdsa_private_key.verifying_key().to_address();
log::info!("Operator address: {:?}", operator_addr);
let registry_coordinator =
Expand Down Expand Up @@ -89,14 +91,21 @@ impl<T: Config> AvsRegistryChainWriterTrait for AvsRegistryContractManager<T> {
g1_point.y
);

let signed_msg = bls_key_pair.sign_hashed_to_curve_message(&g1_point);
let signed_msg = bls_key_pair
.sign_hashed_to_curve_message(&g1_point)
.g1_point;
let g1_pubkey_bn254 = bls_key_pair.get_pub_key_g1();
let g2_pubkey_bn254 = bls_key_pair.get_pub_key_g2();
log::info!(
"SIGNED MESSAGE G1POINT: X: {:?}, Y: {:?}",
signed_msg.x,
signed_msg.y
);

let pubkey_reg_params = RegistryCoordinator::PubkeyRegistrationParams {
pubkeyRegistrationSignature: RegistryCoordinator::G1Point {
X: signed_msg.g1_point.x,
Y: signed_msg.g1_point.y,
X: signed_msg.x,
Y: signed_msg.y,
},
pubkeyG1: RegistryCoordinator::G1Point {
X: g1_pubkey_bn254.x,
Expand All @@ -107,6 +116,22 @@ impl<T: Config> AvsRegistryChainWriterTrait for AvsRegistryContractManager<T> {
Y: g2_pubkey_bn254.y,
},
};
log::info!(
"REGISTRY COORDINATOR G1POINT: X: {:?}, Y: {:?}",
pubkey_reg_params.pubkeyRegistrationSignature.X,
pubkey_reg_params.pubkeyRegistrationSignature.Y
);

let signature = g1_point_to_g1_projective(&signed_msg);
// PAIRING TEST
let e1 = ark_bn254::Bn254::pairing(signature.into_affine(), get_g2_generator().unwrap());

let e2 = ark_bn254::Bn254::pairing(
g1_point_to_ark_point(&g1_point),
bls_key_pair.get_pub_key_g2().to_ark_g2(),
);

assert_eq!(e1, e2);

// Generate a random salt and 1 hour expiry for the signature
let mut rng = rand::thread_rng();
Expand Down Expand Up @@ -164,12 +189,14 @@ impl<T: Config> AvsRegistryChainWriterTrait for AvsRegistryContractManager<T> {
expiry: operator_to_avs_registration_sig_expiry,
};

let tx = registry_coordinator.registerOperator(
quorum_numbers,
socket,
pubkey_reg_params,
operator_signature_with_salt_and_expiry,
);
let tx = registry_coordinator
.registerOperator(
quorum_numbers,
socket,
pubkey_reg_params,
operator_signature_with_salt_and_expiry,
)
.from(operator_addr);

let receipt = tx.send().await?.get_receipt().await.unwrap();

Expand Down
14 changes: 7 additions & 7 deletions utils/src/crypto/bls.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
use super::bn254::{
get_g2_generator, map_to_curve, mul_by_generator_g1, point_to_u256, u256_to_point,
};
use crate::types::AvsError;
use alloy_primitives::U256;
use ark_bn254::Fq as F;
Expand All @@ -22,8 +25,6 @@ use std::fs;
use std::ops::Neg;
use std::path::Path;

use super::bn254::{map_to_curve, mul_by_generator_g1, point_to_u256, u256_to_point};

#[derive(Clone, Debug, Serialize, Deserialize)]
struct EncryptedBLSKeyJSONV3 {
pub pub_key: G1Point,
Expand Down Expand Up @@ -356,11 +357,10 @@ impl Signature {
let p_projective = [g1_point_to_ark_point(&p[0]), g1_point_to_ark_point(&p[1])];
let q_projective = [g2_point_to_ark_point(&q[0]), g2_point_to_ark_point(&q[1])];

// // If Pairing Left and Right are equal, then the signature is valid as well
// let g2_gen = g2_point_to_ark_point(&G2Point::generator());
// let pairing_left = Bn254::pairing(self.g1_point.to_ark_g1(), g2_gen);
// let pairing_right = Bn254::pairing(msg_affine, g2_point_to_ark_point(&pubkey.clone()));
// println!("Pairing Comparison: {:?}", pairing_left == pairing_right);
// If Pairing Left and Right are equal, then the signature is valid as well
let e1 = Bn254::pairing(self.g1_point.to_ark_g1(), get_g2_generator().unwrap());
let e2 = Bn254::pairing(msg_affine, g2_point_to_ark_point(&pubkey.clone()));
log::info!("Are e1 and e2 pairings equal? {:?}", e1 == e2);

let pairing_result = Bn254::multi_pairing(p_projective, q_projective);
Ok(pairing_result.0.is_one())
Expand Down
Loading

0 comments on commit c71a1ea

Please sign in to comment.