Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions starstream-ledger-cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ use sha2::{Digest as _, Sha256};
use starstream_ledger::client::http::ClientBuilder;
use starstream_ledger::client::runtime::UtxoCtx;
use starstream_ledger::client::runtime::{Client, Ctx, call_coordination_script, compile_contract};
use starstream_ledger::{Transaction, TransactionInput, TransactionOutput, encode_digest};
use starstream_ledger::{
CardanoCtx, Transaction, TransactionInput, TransactionOutput, encode_digest,
};
use starstream_runtime::Utxo;
use tokio::fs;
use tokio::io::{AsyncRead, AsyncWriteExt as _, stdout};
Expand Down Expand Up @@ -157,6 +159,14 @@ enum ScriptCommand {
#[arg(long = "import", value_name = "PATH")]
imports: Vec<PathBuf>,

/// Cardano block height reported to the script (`cardano#block-height`).
#[arg(long, default_value_t = 0)]
cardano_block_height: i64,

/// Cardano current slot reported to the script (`cardano#current-slot`).
#[arg(long, default_value_t = 0)]
cardano_current_slot: i64,

/// Digest of the published contract, either as multibase multihash or `sha256:HEX`.
#[arg(value_parser = parse_digest)]
digest: [u8; 32],
Expand Down Expand Up @@ -393,6 +403,8 @@ async fn exec(args: Args) -> anyhow::Result<()> {
simulate,
output_transaction,
imports,
cardano_block_height,
cardano_current_slot,
digest,
script,
args,
Expand Down Expand Up @@ -458,7 +470,14 @@ async fn exec(args: Args) -> anyhow::Result<()> {
let mut results = vec![Val::Bool(false); ty.results().len()];

let mut utxos = Vec::default();
let mut store = Store::new(client.engine(), Ctx::default());
let ctx = Ctx {
cardano: CardanoCtx {
block_height: cardano_block_height,
current_slot: cardano_current_slot,
},
..Ctx::default()
};
let mut store = Store::new(client.engine(), ctx);
let (tx, ..) = call_coordination_script(
&mut store,
&imports,
Expand Down
3 changes: 2 additions & 1 deletion starstream-ledger-cli/tests/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use ed25519_dalek::SigningKey;
use sha2::{Digest as _, Sha256};
use starstream_ledger::client::build_publish_envelope;
use starstream_ledger::server::Ledger;
use starstream_ledger::{Publish, Transaction};
use starstream_ledger::{CardanoCtx, Publish, Transaction};
use tempfile::NamedTempFile;
use tokio::fs;
use tokio::process::Command;
Expand Down Expand Up @@ -71,6 +71,7 @@ async fn cli() {
NETWORK,
ADMIN.verifying_key(),
[],
CardanoCtx::default(),
);
let ledger = Arc::new(ledger);
let addr = free_tcp_addr().await.unwrap();
Expand Down
29 changes: 25 additions & 4 deletions starstream-ledger-node/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ use starstream_ledger::client::runtime::{
Client, Contract, Ctx, call_coordination_script, compile_contract,
};
use starstream_ledger::server::Ledger;
use starstream_ledger::{TransactionInput, TransactionOutput, encode_digest, parse_digest};
use starstream_ledger::{
CardanoCtx, TransactionInput, TransactionOutput, encode_digest, parse_digest,
};
use tokio::fs;
use tokio::signal;
use tokio::time::timeout;
Expand Down Expand Up @@ -58,6 +60,14 @@ pub struct Args {
/// Paths to contracts used to resolve genesis coordination script calls.
#[arg(long = "import", value_name = "PATH", requires = "genesis")]
imports: Vec<PathBuf>,

/// Cardano block height reported to contracts (`cardano#block-height`).
#[arg(long, default_value_t = 0)]
cardano_block_height: i64,

/// Cardano current slot reported to contracts (`cardano#current-slot`).
#[arg(long, default_value_t = 0)]
cardano_current_slot: i64,
}

#[derive(Debug, Deserialize)]
Expand Down Expand Up @@ -107,6 +117,7 @@ async fn build_genesis(
engine: &wasmtime::Engine,
genesis: impl AsRef<Path>,
imports: Vec<PathBuf>,
cardano: CardanoCtx,
) -> anyhow::Result<Vec<TransactionOutput>> {
let genesis = genesis.as_ref();
let genesis = fs::read_to_string(genesis)
Expand Down Expand Up @@ -167,8 +178,12 @@ async fn build_genesis(
}
ensure!(args.next().is_none(), "trailing arguments");
let mut results = vec![Val::Bool(false); ty.results().len()];
let ctx = Ctx {
cardano,
..Ctx::default()
};
let (tx, ..) = call_coordination_script(
&mut Store::new(engine, Ctx::default()),
&mut Store::new(engine, ctx),
&GenesisClient(&imported),
&wizer,
&contract,
Expand Down Expand Up @@ -213,20 +228,26 @@ async fn exec(args: Args) -> anyhow::Result<()> {
shutdown_timeout,
genesis,
imports,
cardano_block_height,
cardano_current_slot,
} = args;
let shutdown_timeout = Duration::from_secs(shutdown_timeout);
let cardano = CardanoCtx {
block_height: cardano_block_height,
current_slot: cardano_current_slot,
};

let mut config = wasmtime::Config::default();
config.wasm_component_model_implements(true);
let engine = wasmtime::Engine::new(&config)?;

let genesis = if let Some(genesis) = genesis {
build_genesis(&engine, genesis, imports).await?
build_genesis(&engine, genesis, imports, cardano).await?
} else {
Vec::default()
};

let ledger = Ledger::new(engine, max_requests, network, admin, genesis);
let ledger = Ledger::new(engine, max_requests, network, admin, genesis, cardano);
let ledger = Arc::new(ledger);

let (http, http_shutdown) = ledger.handle_http(addr).await?;
Expand Down
8 changes: 5 additions & 3 deletions starstream-ledger/src/client/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ use crate::client::CoordinationScriptArg;
use crate::runtime::{apply_state, parse_state};
use crate::wrpc::codec::{ValEncoder, read_value};
use crate::{
Transaction, TransactionEvent, TransactionInput, TransactionOutput, encode_digest, parse_digest,
CardanoCtx, Transaction, TransactionEvent, TransactionInput, TransactionOutput, encode_digest,
parse_digest,
};

/// Contract compiled from the instrumented component bytes
Expand Down Expand Up @@ -459,6 +460,7 @@ pub struct Ctx {
pub events: Vec<TransactionEvent>,
pub outputs: Vec<starstream_runtime::Utxo<<Self as starstream_runtime::Host>::UtxoContext>>,
pub traces: WasmtimeTraceRegistry,
pub cardano: CardanoCtx,
}

#[derive(Clone, Debug)]
Expand Down Expand Up @@ -486,11 +488,11 @@ impl WasmTraceSink for Ctx {

impl starstream::std::cardano::Host for Ctx {
fn block_height(&mut self) -> wasmtime::Result<i64> {
bail!("TODO")
Ok(self.cardano.block_height)
}

fn current_slot(&mut self) -> wasmtime::Result<i64> {
bail!("TODO")
Ok(self.cardano.current_slot)
}
}

Expand Down
10 changes: 10 additions & 0 deletions starstream-ledger/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,16 @@ pub struct Block {
pub actions: Box<[Action]>,
}

/// The Cardano context a contract can observe via the `starstream:std/cardano`
/// host functions.
#[derive(Clone, Copy, Debug, Default)]
pub struct CardanoCtx {
/// Block height reported to the guest via `cardano#block-height`.
pub block_height: i64,
/// Current slot reported to the guest via `cardano#current-slot`.
pub current_slot: i64,
}

#[derive(Debug, Error)]
pub enum DigestParseError {
#[error(transparent)]
Expand Down
6 changes: 5 additions & 1 deletion starstream-ledger/src/server/http/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -701,7 +701,11 @@ impl Ledger {
.push(Arc::clone(&cx))
.map_err(RpcPostError::ResourceTable)?;

let mut store = wasmtime::Store::new(&self.engine, Ctx { table });
let ctx = Ctx {
table,
cardano: self.cardano,
};
let mut store = wasmtime::Store::new(&self.engine, ctx);
let cx_res = cx_res
.try_into_resource_any(&mut store)
.map_err(RpcPostError::Runtime)?;
Expand Down
6 changes: 5 additions & 1 deletion starstream-ledger/src/server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use wasmtime::component::{Component, ResourceTable};
use wasmtime::error::Context as _;

use crate::wrpc::bindings;
use crate::{Block, TransactionOutput, parse_digest};
use crate::{Block, CardanoCtx, TransactionOutput, parse_digest};

mod http;
mod runtime;
Expand Down Expand Up @@ -45,6 +45,7 @@ struct AdminAccount {
#[derive(Debug, Default)]
struct Ctx {
table: ResourceTable,
cardano: CardanoCtx,
}

#[derive(Debug)]
Expand Down Expand Up @@ -79,6 +80,7 @@ pub struct Ledger {
admin: AdminAccount,
genesis: Genesis,
network: Arc<str>,
cardano: CardanoCtx,
max_requests: u32,
permits: Semaphore,
}
Expand All @@ -90,6 +92,7 @@ impl Ledger {
network: impl Into<Arc<str>>,
admin: VerifyingKey,
genesis: impl Into<Box<[TransactionOutput]>>,
cardano: CardanoCtx,
) -> Self {
let max_requests = usize::try_from(max_requests)
.unwrap_or(Semaphore::MAX_PERMITS)
Expand Down Expand Up @@ -118,6 +121,7 @@ impl Ledger {
encoded: encoded.freeze(),
},
network: network.into(),
cardano,
max_requests: max_requests as _,
permits: Semaphore::new(max_requests),
}
Expand Down
4 changes: 2 additions & 2 deletions starstream-ledger/src/server/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ use crate::server::{Ctx, UtxoCtx};

impl starstream::std::cardano::Host for Ctx {
fn block_height(&mut self) -> wasmtime::Result<i64> {
bail!("TODO")
Ok(self.cardano.block_height)
}

fn current_slot(&mut self) -> wasmtime::Result<i64> {
bail!("TODO")
Ok(self.cardano.current_slot)
}
}

Expand Down
13 changes: 10 additions & 3 deletions starstream-ledger/tests/ledger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ use starstream_ledger::client::runtime::compile_contract;
use starstream_ledger::server::Ledger;
use starstream_ledger::wrpc::codec::ValEncoder;
use starstream_ledger::{
APPLICATION_COSE, Envelope, Message, Transaction, TransactionInput, TransactionOutput,
encode_digest,
APPLICATION_COSE, CardanoCtx, Envelope, Message, Transaction, TransactionInput,
TransactionOutput, encode_digest,
};
use tokio::io::AsyncReadExt as _;
use tokio_util::codec::Encoder as _;
Expand Down Expand Up @@ -151,7 +151,14 @@ async fn http() {
score_progress_genesis_utxo,
];

let ledger = Ledger::new(engine, 128, NETWORK, ADMIN.verifying_key(), genesis.clone());
let ledger = Ledger::new(
engine,
128,
NETWORK,
ADMIN.verifying_key(),
genesis.clone(),
CardanoCtx::default(),
);
let ledger = Arc::new(ledger);
let addr = free_tcp_addr().await.unwrap();
let (ledger, shutdown) = ledger.handle_http(addr).await.unwrap();
Expand Down