Skip to content

Commit e15f3e8

Browse files
committed
chore: format all files
1 parent dd84daa commit e15f3e8

File tree

18 files changed

+223
-186
lines changed

18 files changed

+223
-186
lines changed
Lines changed: 67 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
1-
use std::{collections::HashMap};
2-
use std::sync::Arc;
31
use anyhow::{Context, anyhow};
2+
use std::collections::HashMap;
3+
use std::sync::Arc;
44

5-
use wasmtime::*;
6-
use wasmtime::component::{Component, Linker};
75
use p3_field::PrimeField64;
6+
use wasmtime::component::{Component, Linker};
7+
use wasmtime::*;
88

9-
use crate::utxo::{UtxoId, UtxoInstance, UtxoRegistry};
109
use crate::utils::hash::poseidon2_hash_bytes;
10+
use crate::utxo::{UtxoId, UtxoInstance, UtxoRegistry};
1111

1212
pub struct Chain {
1313
utxos: UtxoRegistry,
@@ -17,76 +17,86 @@ pub struct Chain {
1717
pub type WasmComponent = Vec<u8>;
1818

1919
impl Chain {
20-
pub fn new(genesis_block: &Vec<WasmComponent>) -> anyhow::Result<Self> {
21-
let mut utxos = HashMap::new();
20+
pub fn new(genesis_block: &Vec<WasmComponent>) -> anyhow::Result<Self> {
21+
let mut utxos = HashMap::new();
22+
23+
let mut config = wasmtime::Config::default();
24+
config.async_support(true);
25+
let engine = Engine::new(&config)?;
2226

23-
let mut config = wasmtime::Config::default();
24-
config.async_support(true);
25-
let engine = Engine::new(&config)?;
27+
// load genesis block
28+
{
29+
for component_bytes in genesis_block {
30+
let component = Component::new(&engine, component_bytes)
31+
.context("failed to parse component")?;
2632

27-
// load genesis block
28-
{
29-
for component_bytes in genesis_block {
30-
let component = Component::new(&engine, component_bytes)
31-
.context("failed to parse component")?;
33+
// TODO: inject context imports into linker: inject_context_imports
34+
let linker = Linker::new(&engine);
35+
let instance_pre = linker.instantiate_pre(&component)?;
3236

33-
// TODO: inject context imports into linker: inject_context_imports
34-
let linker = Linker::new(&engine);
35-
let instance_pre = linker.instantiate_pre(&component)?;
36-
37-
let digest = poseidon2_hash_bytes(component_bytes);
38-
let contract_hash = format!("0x{:016X}{:016X}{:016X}{:016X}", digest[0].as_canonical_u64(), digest[1].as_canonical_u64(), digest[2].as_canonical_u64(), digest[3].as_canonical_u64());
37+
let digest = poseidon2_hash_bytes(component_bytes);
38+
let contract_hash = format!(
39+
"0x{:016X}{:016X}{:016X}{:016X}",
40+
digest[0].as_canonical_u64(),
41+
digest[1].as_canonical_u64(),
42+
digest[2].as_canonical_u64(),
43+
digest[3].as_canonical_u64()
44+
);
3945

40-
// Register the utxo
41-
utxos.insert(
42-
UtxoId::new(contract_hash, 0),
43-
UtxoInstance {
44-
wasm_instance: Arc::new(instance_pre),
45-
datum: vec![] // TODO: maybe some genesis UTXOs require storage initialization
46-
},
47-
);
46+
// Register the utxo
47+
utxos.insert(
48+
UtxoId::new(contract_hash, 0),
49+
UtxoInstance {
50+
wasm_instance: Arc::new(instance_pre),
51+
datum: vec![], // TODO: maybe some genesis UTXOs require storage initialization
52+
},
53+
);
54+
}
4855
}
49-
}
5056

51-
Ok(Self {
52-
engine: Arc::new(engine),
53-
utxos: tokio::sync::RwLock::new(utxos),
54-
})
55-
}
57+
Ok(Self {
58+
engine: Arc::new(engine),
59+
utxos: tokio::sync::RwLock::new(utxos),
60+
})
61+
}
5662

57-
pub fn engine(&self) -> Arc<Engine> {
58-
self.engine.clone()
59-
}
63+
pub fn engine(&self) -> Arc<Engine> {
64+
self.engine.clone()
65+
}
6066

61-
pub async fn get_utxo(&self, contract_hash: String, serial: u64) -> anyhow::Result<UtxoInstance> {
62-
self.get_utxo_by_id(&UtxoId::new(contract_hash, serial)).await
63-
}
67+
pub async fn get_utxo(
68+
&self,
69+
contract_hash: String,
70+
serial: u64,
71+
) -> anyhow::Result<UtxoInstance> {
72+
self.get_utxo_by_id(&UtxoId::new(contract_hash, serial))
73+
.await
74+
}
6475

65-
pub async fn get_utxo_by_id(&self, id: &UtxoId) -> anyhow::Result<UtxoInstance> {
66-
let utxos = self.utxos.read().await;
67-
let utxo = utxos
68-
.get(id)
69-
.cloned()
70-
.ok_or_else(|| anyhow!("UTXO not found"))?;
71-
Ok(utxo)
72-
}
76+
pub async fn get_utxo_by_id(&self, id: &UtxoId) -> anyhow::Result<UtxoInstance> {
77+
let utxos = self.utxos.read().await;
78+
let utxo = utxos
79+
.get(id)
80+
.cloned()
81+
.ok_or_else(|| anyhow!("UTXO not found"))?;
82+
Ok(utxo)
83+
}
7384
}
7485

75-
7686
/// Host any context that can be fetched from Starstream contracts through an effect handler
7787
///
7888
/// Think of this similar to a React Context: Starstream programs can raise an effect to receive context from the runtime
7989
/// This is represented as an interface (in the WIT definition of the word) that the host provides when it calls into the UTXO
8090
/// (pseudocode as the Starstream syntax isn't decided yet): `raise Ctx.Caller()`
81-
///
91+
///
8292
/// Here, the ledger is the "host" in the WASM sense
8393
/// and it exposes this data to guests via host functions added to the Linker
84-
///
94+
///
8595
/// Note: blockchain execution doesn't involve stateful handles like file descriptors or network connections
8696
/// so it can be an interface, and not a "resource"
8797
fn inject_context_imports() {
88-
// TODO: Add ledger context fields as needed:
89-
// pub block_range: (u64, u64), // validity interval of tx
90-
// pub timestamp_range: (u64, u64), // validity interval of tx
91-
// pub caller_address: String
92-
}
98+
// TODO: Add ledger context fields as needed:
99+
// pub block_range: (u64, u64), // validity interval of tx
100+
// pub timestamp_range: (u64, u64), // validity interval of tx
101+
// pub caller_address: String
102+
}

mock-ledger/backend/ledger/src/encode.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1+
use core::time::Duration;
12
use tokio::io::{DuplexStream, ReadHalf, WriteHalf};
23
use wasmtime::component::ResourceTable;
34
use wasmtime_wasi::{WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView};
45
use wrpc_runtime_wasmtime::{SharedResourceTable, WrpcCtxView, WrpcView};
56
use wrpc_transport::Invoke;
6-
use core::time::Duration;
77
use wrpc_transport::frame::Oneshot;
88

99
pub type InMemoryTransport = Oneshot<ReadHalf<DuplexStream>, WriteHalf<DuplexStream>>;
@@ -81,4 +81,4 @@ pub fn gen_ctx<C: Invoke>(wrpc: C, cx: C::Context) -> Ctx<C> {
8181
timeout: Duration::from_secs(10),
8282
},
8383
}
84-
}
84+
}
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
pub mod chain;
2-
pub mod utxo;
3-
pub mod utils;
42
pub mod encode;
3+
pub mod utils;
4+
pub mod utxo;
55
pub use chain::*;
Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,20 @@
1+
use once_cell::sync::Lazy;
2+
use p3_field::PrimeCharacteristicRing;
13
use p3_goldilocks::{Goldilocks, Poseidon2Goldilocks};
2-
use p3_field::{PrimeCharacteristicRing};
3-
use p3_symmetric::PaddingFreeSponge;
44
use p3_symmetric::CryptographicHasher;
5-
use rand::{rngs::StdRng, SeedableRng};
6-
use once_cell::sync::Lazy;
5+
use p3_symmetric::PaddingFreeSponge;
6+
use rand::{SeedableRng, rngs::StdRng};
77

88
// capacity = WIDTH - RATE = 4 bytes = 256 bytes of pre-image security = 128 bits of collision resistance
99
const WIDTH: usize = 8; // recommended parameter
10-
const RATE: usize = 4; // Run permutation on 4 elements at a time (~256 bits). Must be < WIDTH
11-
const OUT: usize = 4; // 4*64= ~256 bit output (slightly lower as goldilocks is not quite 64-bits)
10+
const RATE: usize = 4; // Run permutation on 4 elements at a time (~256 bits). Must be < WIDTH
11+
const OUT: usize = 4; // 4*64= ~256 bit output (slightly lower as goldilocks is not quite 64-bits)
1212

1313
static HASHER: Lazy<Hash> = Lazy::new(|| {
14-
// constant seed so contract hashes are deterministic
15-
let mut rng = StdRng::seed_from_u64(0);
16-
let perm = Perm::new_from_rng_128(&mut rng);
17-
Hash::new(perm)
14+
// constant seed so contract hashes are deterministic
15+
let mut rng = StdRng::seed_from_u64(0);
16+
let perm = Perm::new_from_rng_128(&mut rng);
17+
Hash::new(perm)
1818
});
1919

2020
type Perm = Poseidon2Goldilocks<WIDTH>;
@@ -24,7 +24,7 @@ type Hash = PaddingFreeSponge<Perm, WIDTH, RATE, OUT>;
2424
* Outputs a 256-bit hash from input bytes.
2525
*/
2626
pub fn poseidon2_hash_bytes(bytes: &[u8]) -> [Goldilocks; OUT] {
27-
let field_iter = bytes
27+
let field_iter = bytes
2828
// Goldilocks field modulus: p = 2^64 - 2^32 + 1
2929
// therefore 8 bytes may not fit, so we use 7 instead
3030
.chunks(7)
@@ -38,5 +38,5 @@ pub fn poseidon2_hash_bytes(bytes: &[u8]) -> [Goldilocks; OUT] {
3838
Goldilocks::from_u64(word)
3939
});
4040

41-
HASHER.hash_iter(field_iter)
41+
HASHER.hash_iter(field_iter)
4242
}
Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1 @@
11
pub mod hash;
2-

mock-ledger/backend/ledger/src/utxo.rs

Lines changed: 24 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,38 @@
1-
use std::sync::Arc;
21
use std::collections::HashMap;
3-
use wasmtime::component::{InstancePre};
2+
use std::sync::Arc;
3+
use wasmtime::component::InstancePre;
44

5-
use crate::encode::{InMemoryTransport, Ctx};
5+
use crate::encode::{Ctx, InMemoryTransport};
66

77
#[derive(Clone)]
88
pub struct UtxoInstance {
9-
/// Cached setup for hydrating a UTXO. Combine it with the datum to initialize
10-
/// InstancePre is immutable and cloneable, so Arc is sufficient for shared ownership
11-
pub wasm_instance: Arc<InstancePre<Ctx<InMemoryTransport>>>,
12-
/// UTXO datum encoded using the WASM Component value encoding
13-
pub datum: Vec<u8>
9+
/// Cached setup for hydrating a UTXO. Combine it with the datum to initialize
10+
/// InstancePre is immutable and cloneable, so Arc is sufficient for shared ownership
11+
pub wasm_instance: Arc<InstancePre<Ctx<InMemoryTransport>>>,
12+
/// UTXO datum encoded using the WASM Component value encoding
13+
pub datum: Vec<u8>,
1414
}
1515

1616
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1717
pub struct UtxoId {
18-
/// The contract hash
19-
contract_hash: String,
20-
/// nth occurrence of the contract_hash on chain
21-
serial: u64,
18+
/// The contract hash
19+
contract_hash: String,
20+
/// nth occurrence of the contract_hash on chain
21+
serial: u64,
2222
}
2323
impl UtxoId {
24-
pub fn new(contract_hash: String, serial: u64) -> Self {
25-
Self { contract_hash, serial }
26-
}
27-
pub fn contract_hash(&self) -> &String {
28-
&self.contract_hash
29-
}
30-
pub fn serial(&self) -> u64 {
31-
self.serial
32-
}
24+
pub fn new(contract_hash: String, serial: u64) -> Self {
25+
Self {
26+
contract_hash,
27+
serial,
28+
}
29+
}
30+
pub fn contract_hash(&self) -> &String {
31+
&self.contract_hash
32+
}
33+
pub fn serial(&self) -> u64 {
34+
self.serial
35+
}
3336
}
3437

3538
/// Mapping from UtxoId -> WASM Component

mock-ledger/backend/node-client/src/args_record.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
1+
use crate::rpc;
12
use anyhow::Context as _;
23
use bytes::BytesMut;
34
use wrpc_pack::{pack, unpack};
4-
use crate::rpc;
55

66
pub mod args_record_bindings {
77
wit_bindgen_wrpc::generate!({
88
path: "../node-server/genesis/wit/args-record/wit"
99
});
1010
}
1111

12-
1312
pub async fn explicit_call(
1413
addr: String,
1514
contract_hash: String,
@@ -38,4 +37,4 @@ pub async fn explicit_call(
3837
// you can do better if you have access to the WIT
3938
let result: i64 = unpack(&mut result.into())?;
4039
Ok(result)
41-
}
40+
}

mock-ledger/backend/node-client/src/args_simple.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1+
use crate::rpc;
12
use anyhow::Context as _;
23
use bytes::BytesMut;
34
use wrpc_pack::{pack, unpack};
4-
use crate::rpc;
55

66
pub async fn explicit_call(
77
addr: String,
@@ -28,4 +28,4 @@ pub async fn explicit_call(
2828
// you can do better if you have access to the WIT
2929
let result: i64 = unpack(&mut result.into())?;
3030
Ok(result)
31-
}
31+
}

0 commit comments

Comments
 (0)