Files
biguint
chain_spec_builder
compact
fixed_point
fork_tree
frame_benchmarking
frame_benchmarking_cli
frame_election_provider_support
frame_executive
frame_metadata
frame_support
frame_support_procedural
frame_support_procedural_tools
frame_support_procedural_tools_derive
frame_support_test
frame_support_test_pallet
frame_system
frame_system_benchmarking
frame_system_rpc_runtime_api
frame_try_runtime
multiply_by_rational
node_bench
node_browser_testing
node_cli
node_executor
node_inspect
node_primitives
node_rpc
node_rpc_client
node_runtime
node_template
node_template_runtime
node_testing
normalize
pallet_assets
pallet_atomic_swap
pallet_aura
pallet_authority_discovery
pallet_authorship
pallet_babe
pallet_balances
pallet_bounties
pallet_collective
pallet_contracts
pallet_contracts_primitives
pallet_contracts_proc_macro
pallet_contracts_rpc
pallet_contracts_rpc_runtime_api
pallet_democracy
pallet_election_provider_multi_phase
pallet_elections
pallet_elections_phragmen
pallet_example
pallet_example_offchain_worker
pallet_example_parallel
pallet_gilt
pallet_grandpa
pallet_identity
pallet_im_online
pallet_indices
pallet_lottery
pallet_membership
pallet_mmr
pallet_mmr_primitives
pallet_mmr_rpc
pallet_multisig
pallet_nicks
pallet_node_authorization
pallet_offences
pallet_offences_benchmarking
pallet_proxy
pallet_randomness_collective_flip
pallet_recovery
pallet_scheduler
pallet_scored_pool
pallet_session
pallet_session_benchmarking
pallet_society
pallet_staking
pallet_staking_reward_curve
pallet_staking_reward_fn
pallet_sudo
pallet_template
pallet_timestamp
pallet_tips
pallet_transaction_payment
pallet_transaction_payment_rpc
pallet_transaction_payment_rpc_runtime_api
pallet_transaction_storage
pallet_treasury
pallet_uniques
pallet_utility
pallet_vesting
per_thing_rational
phragmen_balancing
phragmen_pjr
phragmms_balancing
reduce
remote_externalities
sc_allocator
sc_authority_discovery
sc_basic_authorship
sc_block_builder
sc_chain_spec
sc_chain_spec_derive
sc_cli
sc_client_api
sc_client_db
sc_consensus
sc_consensus_aura
sc_consensus_babe
sc_consensus_babe_rpc
sc_consensus_epochs
sc_consensus_manual_seal
sc_consensus_pow
sc_consensus_slots
sc_consensus_uncles
sc_executor
sc_executor_common
sc_executor_wasmi
sc_executor_wasmtime
sc_finality_grandpa
sc_finality_grandpa_rpc
sc_informant
sc_keystore
sc_light
sc_network
sc_network_gossip
sc_network_test
sc_offchain
sc_peerset
sc_proposer_metrics
sc_rpc
sc_rpc_api
sc_rpc_server
sc_runtime_test
sc_service
sc_service_test
sc_state_db
sc_sync_state_rpc
sc_telemetry
sc_tracing
sc_tracing_proc_macro
sc_transaction_pool
sc_transaction_pool_api
sp_api
sp_api_proc_macro
sp_application_crypto
sp_application_crypto_test
sp_arithmetic
sp_authority_discovery
sp_authorship
sp_block_builder
sp_blockchain
sp_consensus
sp_consensus_aura
sp_consensus_babe
sp_consensus_pow
sp_consensus_slots
sp_consensus_vrf
sp_core
sp_database
sp_debug_derive
sp_externalities
sp_finality_grandpa
sp_inherents
sp_io
sp_keyring
sp_keystore
sp_maybe_compressed_blob
sp_npos_elections
sp_npos_elections_solution_type
sp_offchain
sp_panic_handler
sp_rpc
sp_runtime
sp_runtime_interface
sp_runtime_interface_proc_macro
sp_runtime_interface_test
sp_runtime_interface_test_wasm
sp_runtime_interface_test_wasm_deprecated
sp_sandbox
sp_serializer
sp_session
sp_staking
sp_state_machine
sp_std
sp_storage
sp_tasks
sp_test_primitives
sp_timestamp
sp_tracing
sp_transaction_pool
sp_transaction_storage_proof
sp_trie
sp_utils
sp_version
sp_version_proc_macro
sp_wasm_interface
subkey
substrate
substrate_browser_utils
substrate_build_script_utils
substrate_frame_cli
substrate_frame_rpc_support
substrate_frame_rpc_system
substrate_prometheus_endpoint
substrate_test_client
substrate_test_runtime
substrate_test_runtime_client
substrate_test_runtime_transaction_pool
substrate_test_utils
substrate_test_utils_derive
substrate_test_utils_test_crate
substrate_wasm_builder
test_runner
test_runner_example
try_runtime_cli
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
// This file is part of Substrate.

// Copyright (C) 2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! A mechanism for runtime authors to augment the functionality of contracts.
//!
//! The runtime is able to call into any contract and retrieve the result using
//! [`bare_call`](crate::Pallet::bare_call). This already allows customization of runtime
//! behaviour by user generated code (contracts). However, often it is more straightforward
//! to allow the reverse behaviour: The contract calls into the runtime. We call the latter
//! one a "chain extension" because it allows the chain to extend the set of functions that are
//! callable by a contract.
//!
//! In order to create a chain extension the runtime author implements the [`ChainExtension`]
//! trait and declares it in this pallet's [configuration Trait](crate::Config). All types
//! required for this endeavour are defined or re-exported in this module. There is an
//! implementation on `()` which can be used to signal that no chain extension is available.
//!
//! # Security
//!
//! The chain author alone is responsible for the security of the chain extension.
//! This includes avoiding the exposure of exploitable functions and charging the
//! appropriate amount of weight. In order to do so benchmarks must be written and the
//! [`charge_weight`](Environment::charge_weight) function must be called **before**
//! carrying out any action that causes the consumption of the chargeable weight.
//! It cannot be overstated how delicate of a process the creation of a chain extension
//! is. Check whether using [`bare_call`](crate::Pallet::bare_call) suffices for the
//! use case at hand.
//!
//! # Benchmarking
//!
//! The builtin contract callable functions that pallet-contracts provides all have
//! benchmarks that determine the correct weight that an invocation of these functions
//! induces. In order to be able to charge the correct weight for the functions defined
//! by a chain extension benchmarks must be written, too. In the near future this crate
//! will provide the means for easier creation of those specialized benchmarks.
//!
//! # Example
//!
//! The ink! repository maintains an
//! [end-to-end example](https://github.com/paritytech/ink/tree/master/examples/rand-extension)
//! on how to use a chain extension in order to provide new features to ink! contracts.

use crate::{
	gas::ChargedAmount,
	wasm::{Runtime, RuntimeCosts},
	Error,
};
use codec::{Decode, MaxEncodedLen};
use frame_support::weights::Weight;
use sp_runtime::DispatchError;
use sp_std::{marker::PhantomData, vec::Vec};

pub use crate::{exec::Ext, Config};
pub use frame_system::Config as SysConfig;
pub use pallet_contracts_primitives::ReturnFlags;
pub use sp_core::crypto::UncheckedFrom;
pub use state::Init as InitState;

/// Result that returns a [`DispatchError`] on error.
pub type Result<T> = sp_std::result::Result<T, DispatchError>;

/// A trait used to extend the set of contract callable functions.
///
/// In order to create a custom chain extension this trait must be implemented and supplied
/// to the pallet contracts configuration trait as the associated type of the same name.
/// Consult the [module documentation](self) for a general explanation of chain extensions.
pub trait ChainExtension<C: Config> {
	/// Call the chain extension logic.
	///
	/// This is the only function that needs to be implemented in order to write a
	/// chain extensions. It is called whenever a contract calls the `seal_call_chain_extension`
	/// imported wasm function.
	///
	/// # Parameters
	/// - `func_id`: The first argument to `seal_call_chain_extension`. Usually used to
	/// 		determine which function to realize.
	/// - `env`: Access to the remaining arguments and the execution environment.
	///
	/// # Return
	///
	/// In case of `Err` the contract execution is immediately suspended and the passed error
	/// is returned to the caller. Otherwise the value of [`RetVal`] determines the exit
	/// behaviour.
	fn call<E>(func_id: u32, env: Environment<E, InitState>) -> Result<RetVal>
	where
		E: Ext<T = C>,
		<E::T as SysConfig>::AccountId: UncheckedFrom<<E::T as SysConfig>::Hash> + AsRef<[u8]>;

	/// Determines whether chain extensions are enabled for this chain.
	///
	/// The default implementation returns `true`. Therefore it is not necessary to overwrite
	/// this function when implementing a chain extension. In case of `false` the deployment of
	/// a contract that references `seal_call_chain_extension` will be denied and calling this
	/// function will return [`NoChainExtension`](Error::NoChainExtension) without first calling
	/// into [`call`](Self::call).
	fn enabled() -> bool {
		true
	}
}

/// Implementation that indicates that no chain extension is available.
impl<C: Config> ChainExtension<C> for () {
	fn call<E>(_func_id: u32, mut _env: Environment<E, InitState>) -> Result<RetVal>
	where
		E: Ext<T = C>,
		<E::T as SysConfig>::AccountId: UncheckedFrom<<E::T as SysConfig>::Hash> + AsRef<[u8]>,
	{
		// Never called since [`Self::enabled()`] is set to `false`. Because we want to
		// avoid panics at all costs we supply a sensible error value here instead
		// of an `unimplemented!`.
		Err(Error::<E::T>::NoChainExtension.into())
	}

	fn enabled() -> bool {
		false
	}
}

/// Determines the exit behaviour and return value of a chain extension.
pub enum RetVal {
	/// The chain extensions returns the supplied value to its calling contract.
	Converging(u32),
	/// The control does **not** return to the calling contract.
	///
	/// Use this to stop the execution of the contract when the chain extension returns.
	/// The semantic is the same as for calling `seal_return`: The control returns to
	/// the caller of the currently executing contract yielding the supplied buffer and
	/// flags.
	Diverging { flags: ReturnFlags, data: Vec<u8> },
}

/// Grants the chain extension access to its parameters and execution environment.
///
/// It uses [typestate programming](https://docs.rust-embedded.org/book/static-guarantees/typestate-programming.html)
/// to enforce the correct usage of the parameters passed to the chain extension.
pub struct Environment<'a, 'b, E: Ext, S: state::State> {
	/// The actual data of this type.
	inner: Inner<'a, 'b, E>,
	/// `S` is only used in the type system but never as value.
	phantom: PhantomData<S>,
}

/// Functions that are available in every state of this type.
impl<'a, 'b, E: Ext, S: state::State> Environment<'a, 'b, E, S>
where
	<E::T as SysConfig>::AccountId: UncheckedFrom<<E::T as SysConfig>::Hash> + AsRef<[u8]>,
{
	/// Charge the passed `amount` of weight from the overall limit.
	///
	/// It returns `Ok` when there the remaining weight budget is larger than the passed
	/// `weight`. It returns `Err` otherwise. In this case the chain extension should
	/// abort the execution and pass through the error.
	///
	/// The returned value can be used to with [`Self::adjust_weight`]. Other than that
	/// it has no purpose.
	///
	/// # Note
	///
	/// Weight is synonymous with gas in substrate.
	pub fn charge_weight(&mut self, amount: Weight) -> Result<ChargedAmount> {
		self.inner.runtime.charge_gas(RuntimeCosts::ChainExtension(amount))
	}

	/// Adjust a previously charged amount down to its actual amount.
	///
	/// This is when a maximum a priori amount was charged and then should be partially
	/// refunded to match the actual amount.
	pub fn adjust_weight(&mut self, charged: ChargedAmount, actual_weight: Weight) {
		self.inner
			.runtime
			.adjust_gas(charged, RuntimeCosts::ChainExtension(actual_weight))
	}

	/// Grants access to the execution environment of the current contract call.
	///
	/// Consult the functions on the returned type before re-implementing those functions.
	pub fn ext(&mut self) -> &mut E {
		self.inner.runtime.ext()
	}
}

/// Functions that are only available in the initial state of this type.
///
/// Those are the functions that determine how the arguments to the chain extensions
/// should be consumed.
impl<'a, 'b, E: Ext> Environment<'a, 'b, E, state::Init> {
	/// Creates a new environment for consumption by a chain extension.
	///
	/// It is only available to this crate because only the wasm runtime module needs to
	/// ever create this type. Chain extensions merely consume it.
	pub(crate) fn new(
		runtime: &'a mut Runtime<'b, E>,
		input_ptr: u32,
		input_len: u32,
		output_ptr: u32,
		output_len_ptr: u32,
	) -> Self {
		Environment {
			inner: Inner { runtime, input_ptr, input_len, output_ptr, output_len_ptr },
			phantom: PhantomData,
		}
	}

	/// Use all arguments as integer values.
	pub fn only_in(self) -> Environment<'a, 'b, E, state::OnlyIn> {
		Environment { inner: self.inner, phantom: PhantomData }
	}

	/// Use input arguments as integer and output arguments as pointer to a buffer.
	pub fn prim_in_buf_out(self) -> Environment<'a, 'b, E, state::PrimInBufOut> {
		Environment { inner: self.inner, phantom: PhantomData }
	}

	/// Use input and output arguments as pointers to a buffer.
	pub fn buf_in_buf_out(self) -> Environment<'a, 'b, E, state::BufInBufOut> {
		Environment { inner: self.inner, phantom: PhantomData }
	}
}

/// Functions to use the input arguments as integers.
impl<'a, 'b, E: Ext, S: state::PrimIn> Environment<'a, 'b, E, S> {
	/// The `input_ptr` argument.
	pub fn val0(&self) -> u32 {
		self.inner.input_ptr
	}

	/// The `input_len` argument.
	pub fn val1(&self) -> u32 {
		self.inner.input_len
	}
}

/// Functions to use the output arguments as integers.
impl<'a, 'b, E: Ext, S: state::PrimOut> Environment<'a, 'b, E, S> {
	/// The `output_ptr` argument.
	pub fn val2(&self) -> u32 {
		self.inner.output_ptr
	}

	/// The `output_len_ptr` argument.
	pub fn val3(&self) -> u32 {
		self.inner.output_len_ptr
	}
}

/// Functions to use the input arguments as pointer to a buffer.
impl<'a, 'b, E: Ext, S: state::BufIn> Environment<'a, 'b, E, S>
where
	<E::T as SysConfig>::AccountId: UncheckedFrom<<E::T as SysConfig>::Hash> + AsRef<[u8]>,
{
	/// Reads `min(max_len, in_len)` from contract memory.
	///
	/// This does **not** charge any weight. The caller must make sure that the an
	/// appropriate amount of weight is charged **before** reading from contract memory.
	/// The reason for that is that usually the costs for reading data and processing
	/// said data cannot be separated in a benchmark. Therefore a chain extension would
	/// charge the overall costs either using `max_len` (worst case approximation) or using
	/// [`in_len()`](Self::in_len).
	pub fn read(&self, max_len: u32) -> Result<Vec<u8>> {
		self.inner
			.runtime
			.read_sandbox_memory(self.inner.input_ptr, self.inner.input_len.min(max_len))
	}

	/// Reads `min(buffer.len(), in_len) from contract memory.
	///
	/// This takes a mutable pointer to a buffer fills it with data and shrinks it to
	/// the size of the actual data. Apart from supporting pre-allocated buffers it is
	/// equivalent to to [`read()`](Self::read).
	pub fn read_into(&self, buffer: &mut &mut [u8]) -> Result<()> {
		let len = buffer.len();
		let sliced = {
			let buffer = core::mem::take(buffer);
			&mut buffer[..len.min(self.inner.input_len as usize)]
		};
		self.inner.runtime.read_sandbox_memory_into_buf(self.inner.input_ptr, sliced)?;
		*buffer = sliced;
		Ok(())
	}

	/// Reads and decodes a type with a size fixed at compile time from contract memory.
	///
	/// This function is secure and recommended for all input types of fixed size
	/// as long as the cost of reading the memory is included in the overall already charged
	/// weight of the chain extension. This should usually be the case when fixed input types
	/// are used.
	pub fn read_as<T: Decode + MaxEncodedLen>(&mut self) -> Result<T> {
		self.inner.runtime.read_sandbox_memory_as(self.inner.input_ptr)
	}

	/// Reads and decodes a type with a dynamic size from contract memory.
	///
	/// Make sure to include `len` in your weight calculations.
	pub fn read_as_unbounded<T: Decode>(&mut self, len: u32) -> Result<T> {
		self.inner.runtime.read_sandbox_memory_as_unbounded(self.inner.input_ptr, len)
	}

	/// The length of the input as passed in as `input_len`.
	///
	/// A chain extension would use this value to calculate the dynamic part of its
	/// weight. For example a chain extension that calculates the hash of some passed in
	/// bytes would use `in_len` to charge the costs of hashing that amount of bytes.
	/// This also subsumes the act of copying those bytes as a benchmarks measures both.
	pub fn in_len(&self) -> u32 {
		self.inner.input_len
	}
}

/// Functions to use the output arguments as pointer to a buffer.
impl<'a, 'b, E: Ext, S: state::BufOut> Environment<'a, 'b, E, S>
where
	<E::T as SysConfig>::AccountId: UncheckedFrom<<E::T as SysConfig>::Hash> + AsRef<[u8]>,
{
	/// Write the supplied buffer to contract memory.
	///
	/// If the contract supplied buffer is smaller than the passed `buffer` an `Err` is returned.
	/// If `allow_skip` is set to true the contract is allowed to skip the copying of the buffer
	/// by supplying the guard value of `u32::MAX` as `out_ptr`. The
	/// `weight_per_byte` is only charged when the write actually happens and is not skipped or
	/// failed due to a too small output buffer.
	pub fn write(
		&mut self,
		buffer: &[u8],
		allow_skip: bool,
		weight_per_byte: Option<Weight>,
	) -> Result<()> {
		self.inner.runtime.write_sandbox_output(
			self.inner.output_ptr,
			self.inner.output_len_ptr,
			buffer,
			allow_skip,
			|len| {
				weight_per_byte.map(|w| RuntimeCosts::ChainExtension(w.saturating_mul(len.into())))
			},
		)
	}
}

/// The actual data of an `Environment`.
///
/// All data is put into this struct to easily pass it around as part of the typestate
/// pattern. Also it creates the opportunity to box this struct in the future in case it
/// gets too large.
struct Inner<'a, 'b, E: Ext> {
	/// The runtime contains all necessary functions to interact with the running contract.
	runtime: &'a mut Runtime<'b, E>,
	/// Verbatim argument passed to `seal_call_chain_extension`.
	input_ptr: u32,
	/// Verbatim argument passed to `seal_call_chain_extension`.
	input_len: u32,
	/// Verbatim argument passed to `seal_call_chain_extension`.
	output_ptr: u32,
	/// Verbatim argument passed to `seal_call_chain_extension`.
	output_len_ptr: u32,
}

/// Private submodule with public types to prevent other modules from naming them.
mod state {
	pub trait State {}

	pub trait PrimIn: State {}
	pub trait PrimOut: State {}
	pub trait BufIn: State {}
	pub trait BufOut: State {}

	/// The initial state of an [`Environment`](`super::Environment`).
	/// See [typestate programming](https://docs.rust-embedded.org/book/static-guarantees/typestate-programming.html).
	pub enum Init {}
	pub enum OnlyIn {}
	pub enum PrimInBufOut {}
	pub enum BufInBufOut {}

	impl State for Init {}
	impl State for OnlyIn {}
	impl State for PrimInBufOut {}
	impl State for BufInBufOut {}

	impl PrimIn for OnlyIn {}
	impl PrimOut for OnlyIn {}
	impl PrimIn for PrimInBufOut {}
	impl BufOut for PrimInBufOut {}
	impl BufIn for BufInBufOut {}
	impl BufOut for BufInBufOut {}
}