Skip to content

Commit

Permalink
Cleanup (#11)
Browse files Browse the repository at this point in the history
* delete unused kzg settings dump

* enable resumption of pruneChildren

* prune before resolution

* consider timeout when evaluating winner

* labeled proofs

* update documented fpvm id
  • Loading branch information
hashcashier authored Jan 6, 2025
1 parent 8be24b7 commit 6e2ce8f
Show file tree
Hide file tree
Showing 14 changed files with 177 additions and 57 deletions.
2 changes: 1 addition & 1 deletion bin/cli/src/db/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,7 @@ impl KailuaDB {
!self
.get_local_proposal(&contender)
.unwrap()
.wins_against(proposal)
.wins_against(proposal, self.config.timeout)
})
.unwrap_or(true)
{
Expand Down
51 changes: 42 additions & 9 deletions bin/cli/src/db/proposal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ use serde::{Deserialize, Serialize};
use std::iter::repeat;
use tracing::{error, info, warn};

pub const ELIMINATIONS_LIMIT: u64 = 128;

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Proposal {
// pointers
Expand Down Expand Up @@ -197,8 +199,9 @@ impl Proposal {
.await
.parentGame_;
let parent_tournament_instance = KailuaTournament::new(parent_tournament, &provider);
let children = parent_tournament_instance.childCount().call().await?.count_;
let survivor = parent_tournament_instance
.pruneChildren()
.pruneChildren(children)
.call()
.await?
.survivor;
Expand Down Expand Up @@ -343,14 +346,39 @@ impl Proposal {
&self,
provider: P,
) -> anyhow::Result<N::ReceiptResponse> {
self.tournament_contract_instance(provider)
let contract_instance = self.tournament_contract_instance(&provider);
let parent_tournament: Address = contract_instance.parentGame().stall().await.parentGame_;
let parent_tournament_instance = KailuaTournament::new(parent_tournament, &provider);

loop {
let survivor = parent_tournament_instance
.pruneChildren(U256::from(ELIMINATIONS_LIMIT))
.call()
.await?
.survivor;
if !survivor.is_zero() {
break;
}

info!("Eliminating {ELIMINATIONS_LIMIT} opponents before resolution.");
parent_tournament_instance
.pruneChildren(U256::from(ELIMINATIONS_LIMIT))
.send()
.await
.context("KailuaTournament::pruneChildren (send)")?
.get_receipt()
.await
.context("KailuaTournament::pruneChildren (get_receipt)")?;
}

contract_instance
.resolve()
.send()
.await
.context("KailuaTreasury::resolve (send)")?
.context("KailuaTournament::resolve (send)")?
.get_receipt()
.await
.context("KailuaTreasury::resolve (get_receipt)")
.context("KailuaTournament::resolve (get_receipt)")
}

pub fn has_parent(&self) -> bool {
Expand All @@ -372,17 +400,22 @@ impl Proposal {
None
}

pub fn wins_against(&self, proposal: &Proposal) -> bool {
// todo: If the survivor hasn't been challenged for as long as the timeout, declare them winner
match self.divergence_point(proposal) {
/// Returns true iff self (as contender) wins against opponent
pub fn wins_against(&self, opponent: &Proposal, timeout: u64) -> bool {
// If the survivor hasn't been challenged for as long as the timeout, declare them winner
if opponent.created_at - self.created_at >= timeout {
return true;
}
// Check provable outcome
match self.divergence_point(opponent) {
// u wins if v is a duplicate
None => true,
// u wins if v is wrong (even if u is wrong)
Some(point) => {
if point < self.io_field_elements.len() {
!proposal.correct_io[point].unwrap()
!opponent.correct_io[point].unwrap()
} else {
!proposal.correct_claim.unwrap()
!opponent.correct_claim.unwrap()
}
}
}
Expand Down
17 changes: 15 additions & 2 deletions bin/cli/src/validate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,13 @@ use alloy::eips::eip4844::IndexedBlobHash;
use alloy::eips::BlockNumberOrTag;
use alloy::network::primitives::BlockTransactionsKind;
use alloy::network::EthereumWallet;
use alloy::primitives::{Bytes, FixedBytes, U256};
use alloy::primitives::{Address, Bytes, FixedBytes, U256};
use alloy::providers::{Provider, ProviderBuilder, ReqwestProvider};
use alloy::signers::local::LocalSigner;
use anyhow::{anyhow, bail, Context};
use boundless_market::storage::StorageProviderConfig;
use kailua_client::proof::{fpvm_proof_file_name, Proof};
use kailua_client::BoundlessArgs;
use kailua_client::{parse_address, BoundlessArgs};
use kailua_common::blobs::hash_to_fe;
use kailua_common::blobs::BlobFetchRequest;
use kailua_common::client::config_hash;
Expand Down Expand Up @@ -61,6 +61,8 @@ pub struct ValidateArgs {
/// Secret key of L1 wallet to use for challenging and proving outputs
#[clap(long, env)]
pub validator_key: String,
#[clap(long, value_parser = parse_address, env)]
pub payout_recipient_address: Option<Address>,

#[clap(flatten)]
pub boundless_args: Option<BoundlessArgs>,
Expand Down Expand Up @@ -602,6 +604,7 @@ pub async fn handle_proposals(

match proposal_parent_contract
.prove(
proof_journal.payout_recipient,
[u_index, v_index, challenge_position],
encoded_seal.clone(),
proof_journal.agreed_l2_output_root,
Expand Down Expand Up @@ -778,6 +781,13 @@ pub async fn handle_proofs(
.await?
.l2_chain_id
.to_string();
// Set payout recipient
let payout_recipient = args.payout_recipient_address.unwrap_or_else(|| {
LocalSigner::from_str(&args.validator_key)
.unwrap()
.address()
});
info!("Proof payout recipient: {payout_recipient}");
// Run proof generator loop
loop {
// Dequeue messages
Expand Down Expand Up @@ -810,6 +820,7 @@ pub async fn handle_proofs(
claimed_l2_block_number,
agreed_l2_output_root,
);
let payout_recipient = payout_recipient.to_string();
let l1_head = l1_head.to_string();
let agreed_l2_head_hash = agreed_l2_head_hash.to_string();
let agreed_l2_output_root = agreed_l2_output_root.to_string();
Expand All @@ -821,6 +832,8 @@ pub async fn handle_proofs(
]
.concat();
let mut proving_args = vec![
String::from("--payout-recipient-address"), // wallet address for payouts
payout_recipient,
String::from("--l1-head"), // l1 head from on-chain proposal
l1_head,
String::from("--agreed-l2-head-hash"), // l2 starting block hash from on-chain proposal
Expand Down
13 changes: 12 additions & 1 deletion bin/client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,9 @@ pub struct KailuaClientCli {
#[arg(long, action = clap::ArgAction::Count, env)]
pub kailua_verbosity: u8,

#[clap(long, value_parser = parse_address, env)]
pub payout_recipient_address: Option<Address>,

#[clap(long, value_parser = parse_b256, env)]
pub precondition_validation_data_hash: Option<B256>,

Expand Down Expand Up @@ -187,11 +190,16 @@ pub fn parse_b256(s: &str) -> Result<B256, String> {
B256::from_str(s).map_err(|_| format!("Invalid B256 value: {}", s))
}

pub fn parse_address(s: &str) -> Result<Address, String> {
Address::from_str(s).map_err(|_| format!("Invalid Address value: {}", s))
}

pub async fn run_client<P, H>(
boundless_args: Option<BoundlessArgs>,
boundless_storage_config: Option<StorageProviderConfig>,
oracle_client: P,
hint_client: H,
payout_recipient: Address,
precondition_validation_data_hash: B256,
) -> anyhow::Result<()>
where
Expand All @@ -203,6 +211,7 @@ where
let (journal, witness) = run_native_client(
oracle_client.clone(),
hint_client.clone(),
payout_recipient,
precondition_validation_data_hash,
)
.await
Expand Down Expand Up @@ -245,6 +254,7 @@ where
pub async fn run_native_client<P, H>(
oracle_client: P,
hint_client: H,
payout_recipient: Address,
precondition_validation_data_hash: B256,
) -> anyhow::Result<(ProofJournal, Witness)>
where
Expand Down Expand Up @@ -285,9 +295,10 @@ where
let witness = Witness {
oracle_witness: core::mem::take(oracle_witness.lock().unwrap().deref_mut()),
blobs_witness: core::mem::take(blobs_witness.lock().unwrap().deref_mut()),
payout_recipient_address: payout_recipient,
precondition_validation_data_hash,
};
let journal_output = ProofJournal::new(precondition_hash, boot.as_ref());
let journal_output = ProofJournal::new(payout_recipient, precondition_hash, boot.as_ref());
Ok((journal_output, witness))
}

Expand Down
2 changes: 2 additions & 0 deletions bin/client/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,14 @@ async fn main() -> anyhow::Result<()> {
kona_host::init_tracing_subscriber(args.kailua_verbosity)?;
let precondition_validation_data_hash =
args.precondition_validation_data_hash.unwrap_or_default();
let payout_recipient_address = args.payout_recipient_address.unwrap_or_default();

kailua_client::run_client(
args.boundless_args,
args.boundless_storage_config,
ORACLE_READER,
HINT_WRITER,
payout_recipient_address,
precondition_validation_data_hash,
)
.await
Expand Down
6 changes: 5 additions & 1 deletion bin/host/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@ use alloy::primitives::{keccak256, B256};
use alloy::providers::{Provider, ProviderBuilder, ReqwestProvider};
use alloy_chains::NamedChain;
use alloy_eips::eip4844::IndexedBlobHash;
use alloy_primitives::Address;
use anyhow::bail;
use boundless_market::storage::StorageProviderConfig;
use clap::Parser;
use kailua_client::{parse_b256, BoundlessArgs};
use kailua_client::{parse_address, parse_b256, BoundlessArgs};
use kailua_common::blobs::BlobFetchRequest;
use kailua_common::precondition::PreconditionValidationData;
use kona_host::fetcher::Fetcher;
Expand Down Expand Up @@ -58,6 +59,8 @@ pub struct KailuaHostCli {
/// Whether to skip running the zeth preflight engine
#[clap(long, default_value_t = false, env)]
pub skip_zeth_preflight: bool,
#[clap(long, value_parser = parse_address, env)]
pub payout_recipient_address: Option<Address>,

#[clap(long, default_value_t = 1, env)]
/// Number of blocks to build in a single proof
Expand Down Expand Up @@ -122,6 +125,7 @@ pub async fn start_server_and_native_client(
args.boundless_storage_config,
OracleReader::new(preimage_chan.client),
HintWriter::new(hint_chan.client),
args.payout_recipient_address.unwrap_or_default(),
precondition_validation_data_hash,
));

Expand Down
2 changes: 1 addition & 1 deletion book/src/setup.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ kailua-cli config --op-node-url [YOUR_OP_NODE_URL] --op-geth-url [YOUR_OP_GETH_U
Running the above command against the respective op-sepolia endpoints should produce the following output:
```
RISC0_VERSION: 1.2.0
FPVM_IMAGE_ID: 0x2380494650A313C2A8A32E22CA1D5E42C1E94D1F046607986E73CB9DE3010086
FPVM_IMAGE_ID: 0x49D33C8E46E9FBDB4B3BEBC10473FDC47C4D5E8190CBEECB1B3B2A177149EA6F
CONTROL_ROOT: 0x8CDAD9242664BE3112ABA377C5425A4DF735EB1C6966472B561D2855932C0469
CONTROL_ID: 0x04446E66D300EB7FB45C9726BB53C793DDA407A62E9601618BB43C5C14657AC0
SET_BUILDER_ID: 0x744CCA56CDE6933DEA72752C78B4A6CA894ED620E8AF6437AB05FAD53BCEC40A
Expand Down
19 changes: 14 additions & 5 deletions build/risczero/fpvm/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,23 @@

use alloy_primitives::B256;
use kailua_common::blobs::PreloadedBlobProvider;
use kailua_common::client::log;
use kailua_common::journal::ProofJournal;
use kailua_common::oracle::PreloadedOracle;
use kailua_common::witness::{ArchivedWitness, Witness};
use kona_proof::BootInfo;
use risc0_zkvm::guest::env;
use std::sync::Arc;
use rkyv::rancor::Error;
use kailua_common::client::log;
use std::sync::Arc;

fn main() {
let witness_data = env::read_frame();
log("ACCESS");
let witness_access = rkyv::access::<ArchivedWitness, Error>(&witness_data).expect("Failed to access witness data");
let witness_access = rkyv::access::<ArchivedWitness, Error>(&witness_data)
.expect("Failed to access witness data");
log("DESERIALIZE");
let witness = rkyv::deserialize::<Witness, Error>(witness_access).expect("Failed to deserialize witness");
let witness =
rkyv::deserialize::<Witness, Error>(witness_access).expect("Failed to deserialize witness");
log("RUN");
// let witness: Witness = pot::from_slice(&witness_data).expect("Failed to parse framed witness");
let oracle = Arc::new(PreloadedOracle::from(witness.oracle_witness));
Expand All @@ -55,5 +57,12 @@ fn main() {
assert_eq!(boot.claimed_l2_output_root, B256::ZERO);
}
// Write the proof journal
env::commit_slice(&ProofJournal::new(precondition_hash, boot.as_ref()).encode_packed());
env::commit_slice(
&ProofJournal::new(
witness.payout_recipient_address,
precondition_hash,
boot.as_ref(),
)
.encode_packed(),
);
}
Binary file removed crates/common/kzg_settings_raw.bin
Binary file not shown.
21 changes: 13 additions & 8 deletions crates/common/src/journal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,15 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use alloy_primitives::B256;
use alloy_primitives::{Address, B256};
use anyhow::Context;
use kona_proof::BootInfo;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Clone, Copy, Debug)]
pub struct ProofJournal {
/// The recipient address for the payout
pub payout_recipient: Address,
/// The last finalized L2 output
pub precondition_output: B256,
/// The L1 head hash containing the safe L2 chain data that may reproduce the L2 head hash.
Expand All @@ -34,8 +36,9 @@ pub struct ProofJournal {
}

impl ProofJournal {
pub fn new(precondition_output: B256, boot_info: &BootInfo) -> Self {
pub fn new(payout_recipient: Address, precondition_output: B256, boot_info: &BootInfo) -> Self {
Self {
payout_recipient,
precondition_output,
l1_head: boot_info.l1_head,
agreed_l2_output_root: boot_info.agreed_l2_output_root,
Expand All @@ -49,6 +52,7 @@ impl ProofJournal {
impl ProofJournal {
pub fn encode_packed(&self) -> Vec<u8> {
[
self.payout_recipient.as_slice(),
self.precondition_output.as_slice(),
self.l1_head.as_slice(),
self.agreed_l2_output_root.as_slice(),
Expand All @@ -61,20 +65,21 @@ impl ProofJournal {

pub fn decode_packed(encoded: &[u8]) -> Result<Self, anyhow::Error> {
Ok(ProofJournal {
precondition_output: encoded[..32].try_into().context("precondition_output")?,
l1_head: encoded[32..64].try_into().context("l1_head")?,
agreed_l2_output_root: encoded[64..96]
payout_recipient: encoded[..20].try_into().context("payout_recipient")?,
precondition_output: encoded[20..52].try_into().context("precondition_output")?,
l1_head: encoded[52..84].try_into().context("l1_head")?,
agreed_l2_output_root: encoded[84..116]
.try_into()
.context("agreed_l2_output_root")?,
claimed_l2_output_root: encoded[96..128]
claimed_l2_output_root: encoded[116..148]
.try_into()
.context("claimed_l2_output_root")?,
claimed_l2_block_number: u64::from_be_bytes(
encoded[128..136]
encoded[148..156]
.try_into()
.context("claimed_l2_block_number")?,
),
config_hash: encoded[136..168].try_into().context("config_hash")?,
config_hash: encoded[156..188].try_into().context("config_hash")?,
})
}
}
Loading

0 comments on commit 6e2ce8f

Please sign in to comment.