jam_bootstrap_service/
lib.rs

1//! JAM Bootstrap Service
2//!
3//! Use by concatenating one or more encoded `Instruction`s into a work item's payload.
4
5#![cfg_attr(any(target_arch = "riscv32", target_arch = "riscv64"), no_std)]
6#![allow(clippy::unwrap_used)]
7
8extern crate alloc;
9
10use alloc::{format, string::ToString, vec, vec::Vec};
11use jam_bootstrap_service_common::{Instruction, ServiceRegistry, SERVICE_REGISTRY_KEY};
12use jam_pvm_common::*;
13use jam_types::*;
14
15const BENCHMARK_CYCLES: u32 = 1_000;
16
17pub struct Service;
18jam_pvm_common::declare_service!(Service);
19
20impl jam_pvm_common::Service for Service {
21	fn refine(
22		_core_index: CoreIndex,
23		_item_index: usize,
24		service_id: ServiceId,
25		payload: WorkPayload,
26		_package_hash: WorkPackageHash,
27	) -> WorkOutput {
28		use refine::*;
29		info!(target = "boot", "Bootstrap Service Refine, {service_id:x}h");
30
31		let mut cursor = &payload[..];
32		let mut out = vec![];
33		while !cursor.is_empty() {
34			match Instruction::decode(&mut cursor).unwrap() {
35				Instruction::Lookup { service, hash, eager } if eager => {
36					let maybe_data = foreign_lookup(service, &hash);
37					info!(target = "boot", "Eager lookup, got {:?}", maybe_data);
38					out.push(Instruction::LookedUp { data: maybe_data });
39				},
40				Instruction::RandomStorageRefine(input) =>
41					out.push(Instruction::RandomStorageAccumulate(
42						jam_bootstrap_service_common::test_key_vals::generate_payload(input),
43					)),
44				Instruction::Export { data } => {
45					for d in &data {
46						let r = export_slice(d);
47						info!(target = "boot", "Exported slice: {d:?} -> {r:?}");
48					}
49					out.push(Instruction::Exported { count: data.len() as _ })
50				},
51				Instruction::Import { items } => {
52					let data = items
53						.into_iter()
54						.map(|(index, len)| {
55							import(index as usize).unwrap().truncate_into_vec(len as usize)
56						})
57						.collect();
58					out.push(Instruction::Imported { data });
59				},
60				x => out.push(x),
61			};
62		}
63		debug!(target = "boot", "Returning {:?} into accumulate", out);
64		out.encode().into()
65	}
66
67	fn accumulate(now: Slot, id: ServiceId, _item_count: usize) -> Option<Hash> {
68		use accumulate::*;
69		info!(
70			target = "boot",
71			"Bootstrap Service Accumulate, {id:x}h @{now} ${}",
72			my_info().balance
73		);
74		for item in accumulate::accumulate_items() {
75			match item {
76				AccumulateItem::WorkItem(r) => on_work_item(r, now),
77				AccumulateItem::Transfer(t) => on_transfer(t),
78			}
79		}
80		None
81	}
82}
83
84fn on_work_item(item: WorkItemRecord, now: Slot) {
85	use accumulate::*;
86
87	let Ok(raw_instructions) = item.result else { return };
88
89	for inst in Vec::<Instruction>::decode(&mut &raw_instructions[..]).unwrap() {
90		debug!(target = "boot", "Decoded instruction: {:?}", inst);
91		match inst {
92			Instruction::CreateService {
93				code_hash,
94				code_len,
95				min_item_gas,
96				min_memo_gas,
97				endowment,
98				memo,
99				registration,
100			} => {
101				let id = create_service(&code_hash, code_len as usize, min_item_gas, min_memo_gas);
102				if let Ok(id) = id {
103					info!(target = "boot", "Created service {id:x}h");
104					set(b"created", id).expect("balance?");
105
106					if let Some(code) = lookup(&code_hash) {
107						// Can provide the code right away.
108						let e = provide(id, &code);
109						info!(target = "boot", "Code provision resulted in {e:?}");
110					}
111
112					info!(target = "boot", "Attempting transfer, gas={}", gas());
113					let e = transfer(id, endowment, min_memo_gas, &memo);
114					info!(
115						target = "boot",
116						"Transfer of {endowment} with {min_memo_gas} gas resulted in {e:?}"
117					);
118					if let Some(registration) = registration {
119						let mut registry: ServiceRegistry =
120							get(SERVICE_REGISTRY_KEY).unwrap_or_default();
121						registry.update(registration, id, code_hash);
122						set(SERVICE_REGISTRY_KEY, &registry).expect("balance?");
123					}
124				} else {
125					error!("Failed to create!");
126				}
127			},
128			Instruction::Upgrade { code_hash, min_item_gas, min_memo_gas } => {
129				upgrade(&code_hash, min_item_gas, min_memo_gas);
130				info!(target = "boot", "Upgraded!");
131			},
132			Instruction::Transfer { destination, amount, gas_limit, memo } => {
133				info!(target = "boot", "Gas remaining: {}", gas());
134				info!("Attempting transfer: {} {} {} {:?}", destination, amount, gas_limit, memo);
135				let e = transfer(destination, amount, gas_limit, &memo);
136				info!(target = "boot", "Result: {:?}", e);
137				(destination, amount, memo)
138					.using_encoded(|d| set_storage(b"transferred", d).expect("balance?"));
139			},
140			Instruction::Zombify { ejector } => {
141				info!(target = "boot", "Zombifying service. Ejector: #{:x}", ejector);
142				let info = my_info();
143				if info.bytes >= 81 && info.items == 2 {
144					if forget(&info.code_hash, info.bytes as usize - 81).is_ok() {
145						zombify(ejector);
146						info!(target = "boot", "Zombified");
147					} else {
148						error!("Failed to zombify - invalid code_hash?");
149					}
150				} else {
151					error!("Failed to zombify - laggards in storage/lookup?");
152				}
153			},
154			Instruction::Eject { target, code_hash } => {
155				info!(
156					target = "boot",
157					"Ejecting service #{:x} with code_hash {:?}", target, code_hash
158				);
159				let e = eject(target, &code_hash);
160				info!(target = "boot", "Result: {:?}", e);
161			},
162			Instruction::DeleteItems { storage_items } => {
163				let mut fail = 0;
164				for i in &storage_items {
165					info!(target = "boot", "Deleting item: {:?}", i);
166					if remove_storage(i).is_none() {
167						error!("Failed to remove item: {:?}", i);
168						fail += 1;
169					}
170				}
171				info!(
172					"{} items deleted successfully, {} keys not found",
173					storage_items.len() - fail,
174					fail
175				);
176			},
177			Instruction::Imported { data } => {
178				info!(target = "boot", "Imported data {:?}", data.iter().cloned().map(AnyVec));
179				set_storage(b"imported", &(data.len() as u32).encode()).expect("balance?");
180				for (i, d) in data.into_iter().enumerate() {
181					set_storage(alloc::format!("import-{i}").as_bytes(), &d[..]).expect("balance?");
182				}
183			},
184			Instruction::Exported { count } => {
185				info!(target = "boot", "Exported {count} items");
186				set_storage(b"exported", &count.encode()).expect("balance?");
187			},
188			Instruction::Solicit { hash, len } => {
189				solicit(&hash, len as usize).unwrap();
190				info!(target = "boot", "Solicited {hash} of length {len}");
191				set_storage(b"requested", &hash[..]).expect("balance?");
192			},
193			Instruction::Forget { hash, len } => {
194				let q = query(&hash, len as usize).unwrap();
195				info!(
196					target = "boot",
197					"Query result: {:?} (fi: {:?})",
198					q,
199					q.forget_implication(now)
200				);
201				forget(&hash, len as usize).unwrap();
202				set_storage(b"unrequested", &hash[..]).expect("balance?");
203			},
204			Instruction::Lookup { service, hash, .. } => {
205				let maybe_data = foreign_lookup(service, &hash);
206				info!(target = "boot", "Lookup, got {:?}", maybe_data);
207				if let Some(data) = maybe_data {
208					set_storage(b"looked_up", &data[..]).expect("balance?");
209				} else {
210					remove_storage(b"looked_up");
211				}
212			},
213			Instruction::LookedUp { data } =>
214				if let Some(data) = data {
215					set_storage(b"looked_up", &data[..]).expect("balance?");
216				} else {
217					remove_storage(b"looked_up");
218				},
219			Instruction::Assign { core, queue, assigner } => {
220				info!(target = "boot", "Assigning core {:?} to queue {:?}", core, queue);
221				match assign(core, &queue, assigner) {
222					Ok(_) => info!(target = "boot", "Assigned!"),
223					Err(_) => error!("Failed to assign!"),
224				}
225			},
226			Instruction::Bless { manager, assign, designate, register, auto_acc } => {
227				bless(manager, assign, designate, register, &auto_acc);
228				info!("
229					Blessed services m: #{manager}, a: #{assign}, v: #{designate}, r: #{register}, aa: {auto_acc:?}",
230				);
231			},
232			Instruction::Designate { keys } => match designate(&keys) {
233				Ok(_) => info!(target = "boot", "Designated keys {:?}", keys),
234				Err(_) => error!("Failed to designate"),
235			},
236			Instruction::Yield { hash } => {
237				yield_hash(&hash);
238				info!(target = "boot", "Yielded hash {:?}", hash);
239			},
240			Instruction::Provide { service_id, preimage } => {
241				let r = provide(service_id, &preimage);
242				info!(target = "boot", "Provided preimage to {service_id}: {:?}", r);
243			},
244			Instruction::Checkpoint => {
245				checkpoint();
246				info!(target = "boot", "Checkpointed!");
247			},
248			Instruction::Panic => {
249				panic!("Panic instruction executed!");
250			},
251			Instruction::RandomStorageAccumulate(result_refine) => {
252				if let Ok(keys) = result_refine {
253					let mut count: u64 = get_storage(b"count_random_storage")
254						.map(|v| u64::decode(&mut v.as_slice()).unwrap())
255						.unwrap_or(0);
256					// Warning this instruction is for testing. Most of the work is done in
257					// accumulate which is bad design.
258					for item in keys.items.into_iter() {
259						set_storage(&item.key[..], &item.key[..]).expect("balance?");
260						count += 1;
261					}
262					set_storage(b"count_random_storage", &count.encode()[..]).expect("balance?");
263				}
264			},
265			Instruction::Benchmark =>
266				for i in 0..BENCHMARK_CYCLES {
267					set_storage(format!("item-{now}-{i}").as_bytes(), format!("{i}").as_bytes())
268						.expect("balance low");
269					checkpoint();
270				},
271			i => {
272				info!(target = "boot", "Instruction not handled: {:?}", i);
273			},
274		}
275	}
276}
277
278fn on_transfer(item: TransferRecord) {
279	use accumulate::*;
280	let TransferRecord { source, amount, memo, .. } = item;
281	let count = get::<u32>(b"transfer-count").unwrap_or(0);
282	set(b"transfer-count", count + 1).expect("balance?");
283	info!(
284		target = "boot",
285		"Received transfer from {source} of {amount} with memo {}",
286		alloc::string::String::from_utf8(memo.as_ref().to_vec()).unwrap_or("???".to_string())
287	);
288	set_storage(alloc::format!("transfer{count}").as_bytes(), &(source, amount, memo).encode()[..])
289		.expect("balance?");
290}
291
292pub const MANIFEST_DIR: &str = env!("CARGO_MANIFEST_DIR");